import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sigap/src/features/auth/data/models/kta_model.dart';
import 'package:sigap/src/features/auth/data/models/ktp_model.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/main/registration_form_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/id-card-verification/id_card_verification_controller.dart';
import 'package:sigap/src/shared/widgets/image_upload/image_source_dialog.dart';
import 'package:sigap/src/shared/widgets/image_upload/image_uploader.dart';
import 'package:sigap/src/shared/widgets/info/tips_container.dart';
import 'package:sigap/src/shared/widgets/navigation/step_navigation_buttons.dart';
import 'package:sigap/src/shared/widgets/verification/ocr_result_card.dart';
import 'package:sigap/src/shared/widgets/verification/validation_message_card.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';

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

  @override
  Widget build(BuildContext context) {
    // Initialize form key
    final controller = Get.find<IdCardVerificationController>();
    final mainController = Get.find<FormRegistrationController>();

    final formKey = GlobalKey<FormState>();
    mainController.formKey = formKey;

    final isOfficer = mainController.selectedRole.value?.isOfficer ?? false;

    // Ensure controller's isOfficer flag matches mainController's selected role
    if (controller.isOfficer != isOfficer) {
      controller.updateIsOfficerFlag(isOfficer);
      Logger().i(
        'Updated controller isOfficer flag to match selected role: $isOfficer',
      );
    }

    final String idCardType = isOfficer ? 'KTA' : 'KTP';

    Logger().i(
      'Building IdCardVerificationStep with isOfficer: $isOfficer (Card type: $idCardType)',
    );
    Logger().i('Controller isOfficer flag: ${controller.isOfficer}');

    // Call the debug method to print full controller state
    controller.debugControllerState();

    return Form(
      key: formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(context, idCardType),

          // Error Messages
          Obx(
            () =>
                controller.idCardError.value.isNotEmpty
                    ? Padding(
                      padding: const EdgeInsets.only(top: TSizes.sm),
                      child: Text(
                        controller.idCardError.value,
                        style: TextStyle(color: TColors.error),
                      ),
                    )
                    : const SizedBox.shrink(),
          ),

          // ID Card Upload Widget
          Obx(
            () => ImageUploader(
              image:
                  controller.isIdCardValid.value
                      ? controller.idCardImage.value
                      : null,
              title: 'Upload $idCardType Image',
              subtitle: 'Tap to select an image (max 4MB)',
              errorMessage: controller.idCardError.value,
              isUploading: controller.isUploadingIdCard.value,
              isVerifying: controller.isVerifying.value,
              isConfirmed: controller.hasConfirmedIdCard.value,
              onTapToSelect:
                  () => _showImageSourceDialog(controller, isOfficer),
              onClear: controller.clearIdCardImage,
              onValidate: controller.validateIdCardImage,
              placeholderIcon: Icons.add_a_photo,
              
            ),
          ),

          // OCR Results Card - Using appropriate model
          Obx(() {
            // Display the appropriate model data
            if (controller.isVerifying.value == false &&
                controller.idCardImage.value != null &&
                controller.idCardValidationMessage.value.isNotEmpty &&
                controller.isIdCardValid.value) {
              if (isOfficer && controller.ktaModel.value != null) {
                return _buildKtaResultCard(
                  controller.ktaModel.value!,
                  controller.isIdCardValid.value,
                  context,
                );
              } else if (!isOfficer && controller.ktpModel.value != null) {
                return _buildKtpResultCard(
                  controller.ktpModel.value!,
                  controller.isIdCardValid.value,
                  context,
                );
              } else {
                // Fallback to the regular OCR result card
                return Padding(
                  padding: const EdgeInsets.symmetric(
                    vertical: TSizes.spaceBtwItems,
                  ),
                  child: OcrResultCard(
                    extractedInfo: controller.extractedInfo,
                    isOfficer: isOfficer,
                    isValid: controller.isIdCardValid.value,
                  ),
                );
              }
            }
            return const SizedBox.shrink();
          }),

          // Verification Message for ID Card
          Obx(
            () =>
                controller.idCardValidationMessage.value.isNotEmpty
                    ? Padding(
                      padding: const EdgeInsets.symmetric(
                        vertical: TSizes.spaceBtwItems,
                      ),
                      child: ValidationMessageCard(
                        message: controller.idCardValidationMessage.value,
                        isValid: controller.isIdCardValid.value,
                        hasConfirmed: controller.hasConfirmedIdCard.value,
                        onConfirm: controller.confirmIdCardImage,
                        onTryAnother: controller.clearIdCardImage,
                      ),
                    )
                    : const SizedBox.shrink(),
          ),

          // Tips Section
          const SizedBox(height: TSizes.spaceBtwItems),
          _buildIdCardTips(idCardType),
          
          // Add space before navigation buttons
          const SizedBox(height: TSizes.spaceBtwSections),

          // Navigation buttons with loading state
          Obx(
            () => StepNavigationButtons(
              showPrevious: mainController.currentStep.value > 0,
              isLastStep: false,
              onPrevious: mainController.previousStep,
              onNext: () => _handleNextStep(controller, mainController),
              isLoading:
                  controller.isVerifying.value ||
                  controller.isUploadingIdCard.value,
              errorMessage: controller.idCardError.value,
              nextButtonText: 'Continue',
            ),
          ),
        ],
      ),
    );
  }
  
  // Add a method to handle the next step validation
  void _handleNextStep(
    IdCardVerificationController controller,
    FormRegistrationController mainController,
  ) {
    // Validate that ID card is uploaded and verified
    if (controller.idCardImage.value == null) {
      controller.idCardError.value = 'Please upload your ID card to continue';
      return;
    }

    if (!controller.hasConfirmedIdCard.value) {
      controller.idCardError.value =
          'Your ID card must be confirmed before going to the next step';
      return;
    }

    // If everything is valid, go to next step
    mainController.nextStep();
  }
  
  Widget _buildHeader(BuildContext context, String idCardType) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '$idCardType Verification',
          style: Theme.of(
            context,
          ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: TSizes.sm),
        Text(
          'Upload a clear image of your $idCardType',
          style: Theme.of(context).textTheme.bodyLarge,
        ),
        const SizedBox(height: TSizes.xs),
        Text(
          'Make sure all text and your photo are clearly visible',
          style: Theme.of(
            context,
          ).textTheme.bodySmall?.copyWith(fontStyle: FontStyle.italic),
        ),
        const SizedBox(height: TSizes.spaceBtwItems),
      ],
    );
  }

  Widget _buildIdCardTips(String idCardType) {
    return TipsContainer(
      title: "Tips for a good $idCardType photo:",
      tips: [
        "Place the card on a dark, non-reflective surface",
        "Ensure all four corners are visible",
        "Make sure there's good lighting to avoid shadows",
        "Your photo and all text should be clearly visible",
        "Avoid using flash to prevent glare",
      ],
    );
  }

  void _showImageSourceDialog(
    IdCardVerificationController controller,
    bool isOfficer,
  ) {
    final String idCardType = isOfficer ? 'KTA' : 'KTP';

    ImageSourceDialog.show(
      title: 'Select $idCardType Image Source',
      message:
          'Please ensure your ID card is clear, well-lit, and all text is readable. Maximum file size: 4MB',
      onSourceSelected: controller.pickIdCardImage,
      galleryOption: true,
    );
  }

  Widget _buildKtpResultCard(
    KtpModel model,
    bool isValid,
    BuildContext context,
  ) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: TSizes.spaceBtwItems),
      child: Card(
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
          side: BorderSide(
            color: isValid ? Colors.green : TColors.warning,
            width: 1.5,
          ),
        ),
        child: Padding(
          padding: const EdgeInsets.all(TSizes.md),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildCardHeader('KTP', isValid, context),
              const Divider(height: TSizes.spaceBtwItems),

              // Display KTP details
              if (model.nik.isNotEmpty)
                _buildInfoRow('NIK', model.formattedNik, context),
              if (model.name.isNotEmpty)
                _buildInfoRow('Name', model.name, context),
              if (model.birthPlace.isNotEmpty)
                _buildInfoRow('Birth Place', model.birthPlace, context),
              if (model.birthDate.isNotEmpty)
                _buildInfoRow('Birth Date', model.birthDate, context),
              if (model.gender.isNotEmpty)
                _buildInfoRow('Gender', model.gender, context),
              if (model.address.isNotEmpty)
                _buildInfoRow('Address', model.address, context),

              if (!isValid) _buildDataWarning(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildKtaResultCard(
    KtaModel model,
    bool isValid,
    BuildContext context,
  ) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: TSizes.spaceBtwItems),
      child: Card(
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
          side: BorderSide(
            color: isValid ? Colors.green : TColors.warning,
            width: 1.5,
          ),
        ),
        child: Padding(
          padding: const EdgeInsets.all(TSizes.md),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildCardHeader('KTA', isValid, context),
              const Divider(height: TSizes.spaceBtwItems),

              // Display KTA details
              if (model.name.isNotEmpty)
                _buildInfoRow('Name', model.name, context),
              if (model.nrp.isNotEmpty)
                _buildInfoRow('NRP', model.formattedNrp, context),
              if (model.policeUnit.isNotEmpty)
                _buildInfoRow('Unit', model.policeUnit, context),

              if ((model.position ?? '').isNotEmpty)
                _buildInfoRow('Rank', model.position ?? '', context),

              if (model.issueDate.isNotEmpty)
                _buildInfoRow('Issue Date', model.issueDate, context),
              if (model.cardNumber.isNotEmpty)
                _buildInfoRow('CNumber', model.cardNumber, context),

              if (!isValid) _buildDataWarning(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCardHeader(String cardType, bool isValid, BuildContext context) {
    return Row(
      children: [
        Icon(
          isValid ? Icons.check_circle : Icons.info,
          color: isValid ? Colors.green : TColors.warning,
          size: TSizes.iconMd,
        ),
        const SizedBox(width: TSizes.sm),
        Expanded(
          child: Text(
            'Extracted $cardType Information',
            style: Theme.of(
              context,
            ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
          ),
        ),
      ],
    );
  }

  Widget _buildInfoRow(String label, String value, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: TSizes.sm),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              '$label:',
              style: Theme.of(
                context,
              ).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.bold),
            ),
          ),
          const SizedBox(width: TSizes.sm),
          Expanded(
            child: Text(value, style: Theme.of(context).textTheme.bodyMedium),
          ),
        ],
      ),
    );
  }

  Widget _buildDataWarning() {
    return Container(
      margin: const EdgeInsets.only(top: TSizes.sm),
      padding: const EdgeInsets.all(TSizes.sm),
      decoration: BoxDecoration(
        color: TColors.warning.withOpacity(0.1),
        borderRadius: BorderRadius.circular(TSizes.borderRadiusSm),
      ),
      child: Row(
        children: [
          Icon(
            Icons.warning_amber_rounded,
            color: TColors.warning,
            size: TSizes.iconSm,
          ),
          const SizedBox(width: TSizes.sm),
          Expanded(
            child: Text(
              'Some information might be missing or incorrect. Please verify the extracted data.',
              style: TextStyle(
                fontSize: TSizes.fontSizeXs,
                color: TColors.warning,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
