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';

/// Utility class for debugging the liveness detection and verification process
class LivenessDebugUtils {
  static const String _logName = 'LIVENESS_DEBUG';

  /// Log controller states to console
  static void logControllerStates() {
    try {
      final hasLivenessController = Get.isRegistered<FaceLivenessController>();
      final hasSelfieController =
          Get.isRegistered<SelfieVerificationController>();

      dev.log(
        'Controllers registered: Liveness=$hasLivenessController, Selfie=$hasSelfieController',
        name: _logName,
      );

      if (hasLivenessController) {
        final livenessController = Get.find<FaceLivenessController>();
        dev.log(
          'Liveness controller state: '
          'Status=${livenessController.status.value}, '
          'Camera initialized=${livenessController.cameraController?.value.isInitialized}, '
          'Face in frame=${livenessController.isFaceInFrame}, '
          'Steps=${livenessController.successfulSteps.length}',
          name: _logName,
        );
      }

      if (hasSelfieController) {
        final selfieController = Get.find<SelfieVerificationController>();
        dev.log(
          'Selfie controller state: '
          'HasImage=${selfieController.selfieImage.value != null}, '
          'IsValid=${selfieController.isSelfieValid.value}, '
          'LivenessCheck=${selfieController.isLivenessCheckPassed.value}, '
          'IsPerformingCheck=${selfieController.isPerformingLivenessCheck.value}',
          name: _logName,
        );
      }
    } catch (e) {
      dev.log('Error logging controller states: $e', name: _logName);
    }
  }

  /// Show a debug dialog with controller states
  static void showDebugDialog(BuildContext context) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text('Liveness Debug Info'),
            content: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: _buildDebugInfo(),
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text('Close'),
              ),
              TextButton(
                onPressed: () {
                  logControllerStates();
                  Navigator.of(context).pop();
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Debug info logged to console')),
                  );
                },
                child: Text('Log to Console'),
              ),
            ],
          ),
    );
  }

  /// Build debug information widgets
  static List<Widget> _buildDebugInfo() {
    final List<Widget> info = [];

    try {
      // Check if controllers are registered
      final hasLivenessController = Get.isRegistered<FaceLivenessController>();
      final hasSelfieController =
          Get.isRegistered<SelfieVerificationController>();

      info.add(
        Text('FaceLivenessController: ${hasLivenessController ? "✓" : "✗"}'),
      );
      info.add(
        Text(
          'SelfieVerificationController: ${hasSelfieController ? "✓" : "✗"}',
        ),
      );
      info.add(Divider());

      // Add controller state details if available
      if (hasLivenessController) {
        final controller = Get.find<FaceLivenessController>();
        info.add(
          Text(
            'Liveness Controller',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        );
        info.add(Text('Status: ${controller.status.value}'));
        info.add(
          Text(
            'Camera initialized: ${controller.cameraController?.value.isInitialized}',
          ),
        );
        info.add(Text('Detected face: ${controller.isFaceInFrame}'));
        info.add(Text('Steps completed: ${controller.successfulSteps.length}'));
        info.add(Text('Is captured: ${controller.isCaptured}'));
        info.add(Divider());
      }

      if (hasSelfieController) {
        final controller = Get.find<SelfieVerificationController>();
        info.add(
          Text(
            'Selfie Controller',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        );
        info.add(Text('Has image: ${controller.selfieImage.value != null}'));
        info.add(Text('Is valid: ${controller.isSelfieValid.value}'));
        info.add(
          Text('Liveness passed: ${controller.isLivenessCheckPassed.value}'),
        );
        info.add(
          Text(
            'Performing check: ${controller.isPerformingLivenessCheck.value}',
          ),
        );
      }
    } catch (e) {
      info.add(
        Text(
          'Error getting debug info: $e',
          style: TextStyle(color: Colors.red),
        ),
      );
    }

    return info;
  }

  /// Force reset the controllers for debugging purposes
  static void forceClearControllers() {
    try {
      if (Get.isRegistered<FaceLivenessController>()) {
        final controller = Get.find<FaceLivenessController>();
        controller.resetProcess();
        dev.log('Reset FaceLivenessController', name: _logName);
      }

      if (Get.isRegistered<SelfieVerificationController>()) {
        final controller = Get.find<SelfieVerificationController>();
        // controller.cancelLivenessDetection();
        controller.clearSelfieImage();
        dev.log('Reset SelfieVerificationController', name: _logName);
      }
    } catch (e) {
      dev.log('Error resetting controllers: $e', name: _logName);
    }
  }
}
