import 'dart:developer' as dev;

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/selfie-verification/face_liveness_detection_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/selfie-verification/selfie_verification_controller.dart';
import 'package:sigap/src/features/auth/presentasion/pages/signup/step/selfie-verification/widgets/camera_preview_widget.dart';
import 'package:sigap/src/features/auth/presentasion/pages/signup/step/selfie-verification/widgets/captured_selfie_view.dart';
import 'package:sigap/src/features/auth/presentasion/pages/signup/step/selfie-verification/widgets/countdown_overlay_widget.dart';
import 'package:sigap/src/features/auth/presentasion/pages/signup/step/selfie-verification/widgets/debug_panel.dart';
import 'package:sigap/src/features/auth/presentasion/pages/signup/step/selfie-verification/widgets/verification_progress_widget.dart';
import 'package:sigap/src/shared/widgets/state_screeen/state_screen.dart';
import 'package:sigap/src/utils/constants/colors.dart';

class LivenessDetectionPage extends StatelessWidget {
  const LivenessDetectionPage({super.key});

  @override
  Widget build(BuildContext context) {
    dev.log('Building LivenessDetectionPage', name: 'LIVENESS_DEBUG');

    // Ensure controllers are registered
    final bool hasController = Get.isRegistered<FaceLivenessController>();
    final bool hasSelfieController =
        Get.isRegistered<SelfieVerificationController>();

    dev.log(
      'Controllers registered: FaceLiveness=$hasController, SelfieVerification=$hasSelfieController',
      name: 'LIVENESS_DEBUG',
    );

    final controller =
        hasController
            ? Get.find<FaceLivenessController>()
            : Get.put(FaceLivenessController());

    // Log the initial state of the controller
    dev.log(
      'Controller state: '
      'Camera initialized: ${controller.cameraController?.value.isInitialized}, '
      'Is captured: ${controller.isCaptured}',
      name: 'LIVENESS_DEBUG',
    );

    final selfieController =
        hasSelfieController ? Get.find<SelfieVerificationController>() : null;

    return PopScope(
      onPopInvokedWithResult: (didPop, result) {
        if (Get.isRegistered<FaceLivenessController>()) {
          final controller = Get.find<FaceLivenessController>();
          controller.handleCancellation();
        }
      },
      child: Scaffold(
        backgroundColor: Colors.black,
        extendBodyBehindAppBar: true, // Allow content behind app bar
        appBar: _buildAppBar(context, controller, selfieController),
        body: GetBuilder<FaceLivenessController>(
          builder: (_) {
            // Only access obs values inside Obx
            return Obx(() {
              final isCameraInitialized =
                  controller.cameraController?.value.isInitialized ?? false;
              final hasError = controller.cameraController?.value.hasError;
              final isCaptured = controller.isCaptured.value;
              final status = controller.status.value;

              if (hasError != null && hasError) {
                return StateScreen(
                  icon: Icons.camera_alt_outlined,
                  title: 'Camera Error',
                  subtitle: 'Unable to access camera. Please try again later.',
                );
              }
 
              if (!isCameraInitialized) {
                return _buildCameraInitializingState(controller);
              }

              if (isCaptured) {
                dev.log('Showing captured view', name: 'LIVENESS_DEBUG');
                return CapturedSelfieView(
                  controller: controller,
                  selfieController: selfieController,
                );
              }

              return _buildMainDetectionView(context, controller);
            });
          },
        ),
      ),
    );
  }

  // Building the app bar with debug button
  AppBar _buildAppBar(
    BuildContext context,
    FaceLivenessController controller,
    SelfieVerificationController? selfieController,
  ) {
    return AppBar(
      elevation: 0,
      centerTitle: true,
      backgroundColor: Colors.transparent, // Transparent background
      iconTheme: IconThemeData(color: Colors.white), // White icons
      title: Text(
        'Face Verification',
        style: TextStyle(
          color: Colors.white,
          fontWeight: FontWeight.w600,
          fontSize: 18,
        ),
      ),
      // Debug button
      actions: [
        IconButton(
          icon: Icon(Icons.bug_report, color: Colors.white.withOpacity(0.8)),
          onPressed:
              () =>
                  showLivenessDebugPanel(context, controller, selfieController),
        ),
      ],
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.white),
        onPressed: () {
          dev.log('Back button pressed', name: 'LIVENESS_DEBUG');
          controller.handleCancellation();
          Get.back();
        },
      ),
    );
  }

  // Camera initializing state UI
  Widget _buildCameraInitializingState(FaceLivenessController controller) {
    return Container(
      color: Colors.black,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              color: TColors.primary,
              strokeWidth: 3,
            ),
            SizedBox(height: 24),
            Text(
              'Initializing camera...',
              style: TextStyle(
                fontSize: 16,
                color: Colors.white70,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Main detection view UI with the new layout structure
  Widget _buildMainDetectionView(
    BuildContext context,
    FaceLivenessController controller,
  ) {
    final screenSize = MediaQuery.of(context).size;

    return Stack(
      fit: StackFit.expand,
      children: [
        // Full screen camera preview
        CameraPreviewWidget(
          controller: controller,
          screenWidth: screenSize.width,
        ),

        // Progress indicator at the bottom
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: Container(
            padding: EdgeInsets.only(bottom: 20),
            color: Colors.black.withOpacity(0.5),
            child: VerificationProgressWidget(controller: controller),
          ),
        ),

        // Overlay components including countdown
        CountdownOverlayWidget(controller: controller),
      ],
    );
  }
}
