import 'package:flutter/material.dart';
import 'package:get/get.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/features/auth/presentasion/controllers/signup/step/identity-verification/identity_verification_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/officer-information/officer_info_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/officer-information/unit_info_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/controllers/signup/step/viewer-information/personal_info_controller.dart';
import 'package:sigap/src/shared/widgets/form/form_section_header.dart';
import 'package:sigap/src/shared/widgets/navigation/step_navigation_buttons.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';

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

  @override
  Widget build(BuildContext context) {
    final formKey = GlobalKey<FormState>();
    final mainController = Get.find<FormRegistrationController>();
    final controller = Get.find<IdentityVerificationController>();
    // final personalInfoController = Get.find<PersonalInfoController>();
    // final idCardController = Get.find<IdCardVerificationController>();
    // final selfieController = Get.find<SelfieVerificationController>();

    mainController.formKey = formKey;

    // Extract isOfficer to avoid the error when used in Obx
    final isOfficer = mainController.selectedRole.value?.isOfficer ?? false;

    return Form(
      key: formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Section Header
          FormSectionHeader(
            title: 'Review & Verification',
            subtitle:
                'Please review and confirm your information before submitting',
          ),

          const SizedBox(height: TSizes.spaceBtwItems),

          // Verification Progress Card
          // GetBuilder<IdentityVerificationController>(
          //   builder: (ctrl) => _buildVerificationProgressCard(ctrl),
          // ),
          const SizedBox(height: TSizes.spaceBtwItems),

          // Data Summary Section
          _buildDataSummaryCards(context, isOfficer),

          GetBuilder<IdentityVerificationController>(
            id: 'saveButton',
            builder:
                (ctrl) => ElevatedButton(
                  onPressed:
                      ctrl.isSavingData.value
                          ? null
                          : () => _submitRegistrationData(controller),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: TColors.primary,
                    foregroundColor: Colors.white,
                    minimumSize: const Size(double.infinity, 50),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(TSizes.buttonRadius),
                    ),
                    disabledBackgroundColor: TColors.primary.withOpacity(0.3),
                  ),
                  child:
                      ctrl.isSavingData.value
                          ? const Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: 20,
                                height: 20,
                                child: CircularProgressIndicator(
                                  color: Colors.white,
                                  strokeWidth: 2,
                                ),
                              ),
                              SizedBox(width: TSizes.sm),
                              Text('Submitting...'),
                            ],
                          )
                          : const Text('Submit Registration'),
                ),
          ),

          Obx(
            () => StepNavigationButtons(
              showPrevious: mainController.currentStep.value > 0,
              isLastStep: false,
              onPrevious: mainController.previousStep,
              onNext: () => _submitRegistrationData(controller),
              isLoading: mainController.isSubmitting.value,
              errorMessage: mainController.submitMessage.value,
              nextButtonText: 'Continue',
            ),
          ),

          // Save Result Message
          GetBuilder<IdentityVerificationController>(
            id: 'saveMessage',
            builder:
                (ctrl) =>
                    ctrl.dataSaveMessage.value.isNotEmpty
                        ? Padding(
                          padding: const EdgeInsets.only(top: TSizes.sm),
                          child: Text(
                            ctrl.dataSaveMessage.value,
                            style: TextStyle(
                              color:
                                  ctrl.isDataSaved.value
                                      ? Colors.green
                                      : TColors.error,
                              fontWeight: FontWeight.bold,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        )
                        : const SizedBox.shrink(),
          ),
        ],
      ),
    );
  }

  Widget _buildDataSummaryCards(BuildContext context, bool isOfficer) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // User Profile Information Summary
        _buildUserProfileSummaryCard(context),

        const SizedBox(height: TSizes.spaceBtwItems),

        // ID Card Information Summary
        _buildIdCardSummaryCard(context, isOfficer),

        // Officer Information Card (if applicable)
        if (isOfficer) ...[
          const SizedBox(height: TSizes.spaceBtwItems),
          _buildOfficerInfoSummaryCard(context),
        ],

        const SizedBox(height: TSizes.spaceBtwSections),

        // Divider to separate summary from the form
        Divider(color: Colors.grey.withOpacity(0.3), thickness: 1),

        const SizedBox(height: TSizes.spaceBtwItems),
      ],
    );
  }

  // User Profile Information Summary Card (based on ProfileModel)
  Widget _buildUserProfileSummaryCard(BuildContext context) {
    final personalInfoController = Get.find<PersonalInfoController>();
    final idCardController = Get.find<IdCardVerificationController>();
    final selfieController = Get.find<SelfieVerificationController>();

    return _buildSummaryCard(
      context: context,
      icon: Icons.person,
      title: 'User Profile Information',
      content: [
        _buildInfoRow(
          'First Name',
          personalInfoController.firstNameController.text,
        ),
        _buildInfoRow(
          'Last Name',
          personalInfoController.lastNameController.text,
        ),
        _buildInfoRow('Phone', personalInfoController.phoneController.text),
        _buildInfoRow(
          'Bio',
          personalInfoController.bioController.text.isEmpty
              ? 'Not provided'
              : personalInfoController.bioController.text,
        ),
        _buildInfoRow('Address', personalInfoController.addressController.text),
      ],
      isVerified: true,
    );
  }

  // ID Card Information Summary Card (based on KTP/KTA models)
  Widget _buildIdCardSummaryCard(BuildContext context, bool isOfficer) {
    final idCardController = Get.find<IdCardVerificationController>();

    final List<Widget> idCardInfo = [];
    String cardTitle = '';

    if (isOfficer && idCardController.ktaModel.value != null) {
      cardTitle = 'Police Officer Card (KTA)';
      final kta = idCardController.ktaModel.value!;
      idCardInfo.addAll([
        _buildInfoRow('NRP', kta.formattedNrp),
        _buildInfoRow('Name', kta.name),
        _buildInfoRow('Police Unit', kta.policeUnit),
        if (kta.extraData != null && kta.extraData!['pangkat'] != null)
          _buildInfoRow('Rank', kta.extraData!['pangkat']),
      ]);
    } else if (!isOfficer && idCardController.ktpModel.value != null) {
      cardTitle = 'National ID (KTP)';
      final ktp = idCardController.ktpModel.value!;
      idCardInfo.addAll([
        _buildInfoRow('NIK', ktp.formattedNik),
        _buildInfoRow('Name', ktp.name),
        _buildInfoRow('Birth Place', ktp.birthPlace),
        _buildInfoRow('Birth Date', ktp.birthDate),
        _buildInfoRow('Gender', ktp.gender),
      ]);
    }

    return _buildSummaryCard(
      context: context,
      icon: Icons.badge,
      title: cardTitle,
      content: idCardInfo,
      isVerified: idCardController.isIdCardValid.value,
    );
  }

  // Officer Information Summary Card (based on OfficerModel)
  Widget _buildOfficerInfoSummaryCard(BuildContext context) {
    final officerInfoController = Get.find<OfficerInfoController>();
    final unitInfoController = Get.find<UnitInfoController>();

    final selectedUnit = unitInfoController.availableUnits.firstWhereOrNull(
      (unit) => unit.codeUnit == unitInfoController.unitIdController.text,
    );

    return _buildSummaryCard(
      context: context,
      icon: Icons.security,
      title: 'Officer Information',
      content: [
        _buildInfoRow('NRP', officerInfoController.nrpController.text),
        _buildInfoRow('Rank', officerInfoController.rankController.text),
        _buildInfoRow('Position', unitInfoController.positionController.text),
        _buildInfoRow(
          'Unit',
          selectedUnit?.name ?? unitInfoController.unitIdController.text,
        ),
      ],
      isVerified: true,
    );
  }

  // Generic summary card builder
  Widget _buildSummaryCard({
    required BuildContext context,
    required IconData icon,
    required String title,
    required List<Widget> content,
    required bool isVerified,
  }) {
    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
        side: BorderSide(
          color:
              isVerified
                  ? Colors.green.withOpacity(0.5)
                  : TColors.primary.withOpacity(0.5),
          width: 1,
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.all(TSizes.md),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header
            Row(
              children: [
                Icon(
                  icon,
                  color: isVerified ? Colors.green : TColors.primary,
                  size: TSizes.iconMd,
                ),
                const SizedBox(width: TSizes.sm),
                Text(
                  title,
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: isVerified ? Colors.green : TColors.primary,
                  ),
                ),
                const Spacer(),
                Icon(
                  isVerified ? Icons.check_circle : Icons.info_outline,
                  color: isVerified ? Colors.green : TColors.warning,
                  size: TSizes.iconSm,
                ),
                const SizedBox(width: TSizes.xs),
                Text(
                  isVerified ? 'Verified' : 'Review',
                  style: TextStyle(
                    fontSize: TSizes.fontSizeXs,
                    color: isVerified ? Colors.green : TColors.warning,
                  ),
                ),
              ],
            ),
            const Divider(height: TSizes.spaceBtwItems),

            // Content
            ...content,
          ],
        ),
      ),
    );
  }

  // Helper to build info rows in summary cards
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: TSizes.xs),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              '$label:',
              style: TextStyle(
                fontWeight: FontWeight.w500,
                fontSize: TSizes.fontSizeSm,
                color: TColors.textSecondary,
              ),
            ),
          ),
          Expanded(
            child: Text(value, style: TextStyle(fontSize: TSizes.fontSizeSm)),
          ),
        ],
      ),
    );
  }

  // Build Verification Progress Card
  Widget _buildVerificationProgressCard(
    IdentityVerificationController controller,
  ) {
    // Instead of using Obx, we directly use the current values
    final bool allVerified =
        controller.isPersonalInfoVerified.value &&
        controller.isIdCardVerified.value &&
        controller.isSelfieVerified.value;

    return Container(
      padding: const EdgeInsets.all(TSizes.md),
      decoration: BoxDecoration(
        color:
            allVerified
                ? Colors.green.withOpacity(0.1)
                : TColors.warning.withOpacity(0.1),
        borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
        border: Border.all(
          color:
              allVerified
                  ? Colors.green.withOpacity(0.5)
                  : TColors.warning.withOpacity(0.5),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                allVerified ? Icons.verified : Icons.info_outline,
                color: allVerified ? Colors.green : TColors.warning,
                size: TSizes.iconMd,
              ),
              const SizedBox(width: TSizes.sm),
              Text(
                allVerified
                    ? 'All verification steps completed!'
                    : 'Verification Status',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: allVerified ? Colors.green : TColors.warning,
                ),
              ),
            ],
          ),
          const SizedBox(height: TSizes.sm),

          // Basic Info status
          _buildVerificationItem(
            'Basic Information',
            controller.isPersonalInfoVerified.value,
          ),

          // ID Card status
          _buildVerificationItem(
            'ID Card Verification',
            controller.extractedIdCardNumber!.isNotEmpty,
          ),

          // Selfie status
          _buildVerificationItem(
            'Selfie Verification',
            controller.isSelfieVerified.value,
          ),

          // Identity Verification (this step)
          _buildVerificationItem(
            'Identity Confirmation',
            controller.isFormValid.value,
            isCurrentStep: true,
          ),
        ],
      ),
    );
  }

  // Build verification step item
  Widget _buildVerificationItem(
    String title,
    bool isVerified, {
    bool isCurrentStep = false,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: TSizes.xs),
      child: Row(
        children: [
          Icon(
            isVerified
                ? Icons.check_circle
                : isCurrentStep
                ? Icons.edit
                : Icons.error_outline,
            color:
                isVerified
                    ? Colors.green
                    : isCurrentStep
                    ? TColors.primary
                    : TColors.error,
            size: TSizes.iconSm,
          ),
          const SizedBox(width: TSizes.xs),
          Text(
            title,
            style: TextStyle(
              fontSize: TSizes.fontSizeSm,
              color:
                  isVerified
                      ? Colors.green
                      : isCurrentStep
                      ? TColors.primary
                      : TColors.textSecondary,
              fontWeight: isCurrentStep ? FontWeight.bold : FontWeight.normal,
            ),
          ),
          const Spacer(),
          Text(
            isVerified
                ? 'Verified'
                : isCurrentStep
                ? 'In Progress'
                : 'Not Verified',
            style: TextStyle(
              fontSize: TSizes.fontSizeXs,
              color:
                  isVerified
                      ? Colors.green
                      : isCurrentStep
                      ? TColors.primary
                      : TColors.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  // Submit registration data
  void _submitRegistrationData(
    IdentityVerificationController controller,
  ) async {
    // Call saveRegistrati`onData with all the collected data
    controller.saveRegistrationData();

    // The rest of submission logic would be handled in the controller
  }
}
