import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sigap/src/cores/services/azure_ocr_service.dart';

class ImageVerificationController extends GetxController {
  // Singleton instance
  static ImageVerificationController get instance => Get.find();

  // final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final AzureOCRService _ocrService = AzureOCRService();
  final bool isOfficer;
final RxBool isFormValid = RxBool(true);

  ImageVerificationController({required this.isOfficer});

  // ID Card variables
  final Rx<XFile?> idCardImage = Rx<XFile?>(null);
  final RxString idCardError = RxString('');
  final RxBool isVerifying = RxBool(false);
  final RxBool isIdCardValid = RxBool(false);
  final RxString idCardValidationMessage = RxString('');

  // Loading states for image uploading
  final RxBool isUploadingIdCard = RxBool(false);
  final RxBool isUploadingSelfie = RxBool(false);

  // Face verification variables
  final Rx<XFile?> selfieImage = Rx<XFile?>(null);
  final RxString selfieError = RxString('');
  final RxBool isVerifyingFace = RxBool(false);
  final RxBool isSelfieValid = RxBool(false);
  final RxString selfieValidationMessage = RxString('');
  final RxBool isLivenessCheckPassed = RxBool(false);
  final RxBool isPerformingLivenessCheck = RxBool(false);

  // Confirmation status
  final RxBool hasConfirmedIdCard = RxBool(false);
  final RxBool hasConfirmedSelfie = RxBool(false);

  bool validate() {
    clearErrors();

    // For this step, we just need to ensure both images are uploaded and initially validated
    

    if (idCardImage.value == null) {
      final idCardType = isOfficer ? 'KTA' : 'KTP';
      idCardError.value = 'Please upload your $idCardType image';
      isFormValid.value = false;
    } else if (!isIdCardValid.value) {
      idCardError.value = 'Your ID card image is not valid';
      isFormValid.value = false;
    } else if (!hasConfirmedIdCard.value) {
      idCardError.value = 'Please confirm your ID card image';
      isFormValid.value = false;
    }

    if (selfieImage.value == null) {
      selfieError.value = 'Please take a selfie for verification';
      isFormValid.value = false;
    } else if (!isSelfieValid.value) {
      selfieError.value = 'Your selfie image is not valid';
      isFormValid.value = false;
    } else if (!hasConfirmedSelfie.value) {
      selfieError.value = 'Please confirm your selfie image';
      isFormValid.value = false;
    }

    return isFormValid.value;
  }

  void clearErrors() {
    idCardError.value = '';
    selfieError.value = '';
  }

  // Pick ID Card Image
  Future<void> pickIdCardImage(ImageSource source) async {
    try {
      isUploadingIdCard.value = true;
      hasConfirmedIdCard.value =
          false; // Reset confirmation whenever image changes

      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(
        source: source,
        imageQuality: 80,
      );

      if (image != null) {
        // Add artificial delay to show loading state
        await Future.delayed(const Duration(seconds: 1));
        idCardImage.value = image;
        idCardError.value = '';

        // Initial validation of the ID card (simple check)
        await validateIdCardImage();
      }
    } catch (e) {
      idCardError.value = 'Failed to pick image: $e';
      isIdCardValid.value = false;
    } finally {
      isUploadingIdCard.value = false;
    }
  }

  // Take or pick selfie image
  Future<void> pickSelfieImage(ImageSource source) async {
    try {
      isUploadingSelfie.value = true;
      hasConfirmedSelfie.value =
          false; // Reset confirmation whenever image changes

      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(
        source: source,
        preferredCameraDevice: CameraDevice.front,
        imageQuality: 80,
      );

      if (image != null) {
        // Add artificial delay to show loading state
        await Future.delayed(const Duration(seconds: 1));
        selfieImage.value = image;
        selfieError.value = '';

        // Initial validation of the selfie (face detection)
        await validateSelfieImage();
      }
    } catch (e) {
      selfieError.value = 'Failed to capture selfie: $e';
      isSelfieValid.value = false;
    } finally {
      isUploadingSelfie.value = false;
    }
  }

  // Initial validation of ID card image
  Future<void> validateIdCardImage() async {
    if (idCardImage.value == null) {
      idCardError.value = 'Please upload an ID card image first';
      isIdCardValid.value = false;
      return;
    }

    try {
      isVerifying.value = true;
      final idCardType = isOfficer ? 'KTA' : 'KTP';

      // Basic validation to check if the image is clear enough for OCR
      // Since the _detectFaces method is private, we'll use a public method to detect faces
      // or simulate it for validation purposes
      bool isImageValid = true; // Default to true for now

      try {
        // Try to use processIdCard method to check if the image can be processed properly
        final result = await _ocrService.processIdCard(
          idCardImage.value!,
          isOfficer,
        );
        // If we get here without an exception, the image is likely valid
        isImageValid = result.isNotEmpty;
      } catch (processingError) {
        // If processing fails, the image might not be valid
        isImageValid = false;
      }

      if (isImageValid) {
        isIdCardValid.value = true;
        idCardValidationMessage.value =
            '$idCardType image looks valid. Please confirm this is your $idCardType.';
      } else {
        isIdCardValid.value = false;
        idCardValidationMessage.value =
            'The image doesn\'t appear to be a valid $idCardType. Please upload a clearer image.';
      }
    } catch (e) {
      isIdCardValid.value = false;
      idCardValidationMessage.value = 'Validation failed: ${e.toString()}';
    } finally {
      isVerifying.value = false;
    }
  }

  // Initial validation of selfie image
  Future<void> validateSelfieImage() async {
    if (selfieImage.value == null) {
      selfieError.value = 'Please take a selfie first';
      isSelfieValid.value = false;
      return;
    }

    try {
      isVerifyingFace.value = true;

      // Instead of directly calling _detectFaces, we'll use the liveness check
      // which indirectly checks for faces
      final livenessResult = await _ocrService.performLivenessCheck(
        selfieImage.value!,
      );
      isLivenessCheckPassed.value = livenessResult['isLive'] ?? false;

      if (livenessResult['isLive'] == true) {
        isSelfieValid.value = true;
        selfieValidationMessage.value =
            'Face detected. Please confirm this is you.';
      } else {
        isSelfieValid.value = false;
        selfieValidationMessage.value =
            livenessResult['message'] ??
            'No face detected or liveness check failed. Please take a clearer selfie.';
      }
    } catch (e) {
      isSelfieValid.value = false;
      selfieValidationMessage.value = 'Validation failed: ${e.toString()}';
    } finally {
      isVerifyingFace.value = false;
    }
  }

  // Clear ID Card Image
  void clearIdCardImage() {
    idCardImage.value = null;
    idCardError.value = '';
    isIdCardValid.value = false;
    idCardValidationMessage.value = '';
    hasConfirmedIdCard.value = false;
  }

  // Clear Selfie Image
  void clearSelfieImage() {
    selfieImage.value = null;
    selfieError.value = '';
    isSelfieValid.value = false;
    selfieValidationMessage.value = '';
    isLivenessCheckPassed.value = false;
    hasConfirmedSelfie.value = false;
  }

  // Confirm ID Card Image
  void confirmIdCardImage() {
    if (isIdCardValid.value) {
      hasConfirmedIdCard.value = true;
    }
  }

  // Confirm Selfie Image
  void confirmSelfieImage() {
    if (isSelfieValid.value && isLivenessCheckPassed.value) {
      hasConfirmedSelfie.value = true;
    }
  }
}
