import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:logger/logger.dart';
import 'package:sigap/src/cores/services/supabase_service.dart';
import 'package:sigap/src/features/auth/data/models/registration_data_model.dart';
import 'package:sigap/src/features/auth/data/repositories/authentication_repository.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/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/controllers/signup/step/viewer-information/personal_info_controller.dart';
import 'package:sigap/src/features/daily-ops/data/models/index.dart';
import 'package:sigap/src/features/personalization/data/models/index.dart';
import 'package:sigap/src/features/personalization/data/models/models/user_metadata_model.dart';
import 'package:sigap/src/features/personalization/data/repositories/profile_repository.dart';
import 'package:sigap/src/features/personalization/data/repositories/roles_repository.dart';
import 'package:sigap/src/features/personalization/data/repositories/users_repository.dart';
import 'package:sigap/src/shared/widgets/state_screeen/state_screen.dart';
import 'package:sigap/src/utils/constants/image_strings.dart';
import 'package:sigap/src/utils/constants/num_int.dart';
import 'package:sigap/src/utils/helpers/network_manager.dart';
import 'package:sigap/src/utils/popups/loaders.dart';

class FormRegistrationController extends GetxController {
  static FormRegistrationController get to => Get.find();

  // Centralized registration data model
  final Rx<RegistrationDataModel> registrationData =
      RegistrationDataModel().obs;

  // Role information
  final Rx<RoleModel?> selectedRole = Rx<RoleModel?>(null);

  // Form steps controllers
  late final PersonalInfoController personalInfoController;
  late final IdCardVerificationController idCardVerificationController;
  late final SelfieVerificationController selfieVerificationController;
  late final IdentityVerificationController identityController;
  late final OfficerInfoController? officerInfoController;
  late final UnitInfoController? unitInfoController;

  // Current step in the registration process
  final RxInt currentStep = 0.obs;

  // Total steps based on role
  int get totalSteps =>
      selectedRole.value?.isOfficer ?? false
          ? TNum
              .totalStepOfficer // 3 steps for officers
          : TNum.totalStepViewer; // 4 steps for viewers

  final storage = GetStorage();

  // Loading state for form operations
  final RxBool isLoading = false.obs;

  // Form key for validation
  GlobalKey<FormState>? formKey;

  // User metadata model (kept for backward compatibility)
  final Rx<UserMetadataModel> userMetadata = UserMetadataModel().obs;

  // Viewer data (kept for backward compatibility)
  final Rx<UserModel?> viewerModel = Rx<UserModel?>(null);
  final Rx<ProfileModel?> profileModel = Rx<ProfileModel?>(null);

  // Officer data (kept for backward compatibility)
  final Rx<OfficerModel?> officerModel = Rx<OfficerModel?>(null);

  // Form submission states
  final RxBool isSubmitting = RxBool(false);
  final RxString submitMessage = RxString('');
  final RxBool isSubmitSuccess = RxBool(false);



  @override
  void onInit() {
    super.onInit();
    _initializeSafely();
  }

  /// Initialize safely without triggering redirects
  void _initializeSafely() {
    _initializeControllers();
    Future.microtask(() => _fetchUserDataOnly());
  }

  /// Fetch user data without triggering screen redirects
  Future<void> _fetchUserDataOnly() async {
    try {
      Logger().d('Fetching user data safely without redirects');

      final session = SupabaseService.instance.client.auth.currentSession;

      if (session?.user != null) {
        final user = session!.user;
        Logger().d('Found user session: ${user.id} - ${user.email}');

        // Update registration data with user information
        registrationData.value = registrationData.value.copyWith(
          userId: user.id,
          email: user.email,
          roleId: user.userMetadata?['role_id'] as String?,
          isOfficer: user.userMetadata?['is_officer'] as bool? ?? false,
          profileStatus:
              user.userMetadata?['profile_status'] as String? ?? 'incomplete',
        );

        // Update userMetadata for backward compatibility
        UserMetadataModel metadata = UserMetadataModel(
          userId: user.id,
          email: user.email,
          roleId: user.userMetadata?['role_id'] as String?,
          isOfficer: user.userMetadata?['is_officer'] as bool? ?? false,
          profileStatus:
              user.userMetadata?['profile_status'] as String? ?? 'incomplete',
        );

        if (user.userMetadata != null) {
          try {
            final fullMetadata = UserMetadataModel.fromJson(user.userMetadata);
            metadata = fullMetadata;
            Logger().d('Successfully parsed complete user metadata');
          } catch (e) {
            Logger().w('Could not parse full metadata: $e');
          }
        }

        userMetadata.value = metadata;
        Logger().d('User metadata set: ${userMetadata.value.toString()}');

        await _completeInitialization();
      } else {
        _handleNoActiveSession();
      }
    } catch (e) {
      Logger().e('Error fetching user data: $e');
      registrationData.value = registrationData.value.copyWith(
        profileStatus: 'incomplete',
        isOfficer: false,
      );
    }
  }

  /// Handle case when there's no active session
  void _handleNoActiveSession() {
    try {
      final arguments = Get.arguments;

      if (arguments is Map<String, dynamic> &&
          arguments.containsKey('userId')) {
        registrationData.value = registrationData.value.copyWith(
          userId: arguments['userId'] as String?,
          email: arguments['email'] as String?,
          roleId: arguments['roleId'] as String?,
          isOfficer: arguments['isOfficer'] as bool? ?? false,
          profileStatus: 'incomplete',
        );

        userMetadata.value = UserMetadataModel(
          userId: arguments['userId'] as String?,
          email: arguments['email'] as String?,
          roleId: arguments['roleId'] as String?,
          isOfficer: arguments['isOfficer'] as bool? ?? false,
          profileStatus: 'incomplete',
        );
      } else {
        final tempUserId = storage.read('TEMP_USER_ID') as String?;
        final tempEmail = storage.read('CURRENT_USER_EMAIL') as String?;

        if (tempUserId != null || tempEmail != null) {
          registrationData.value = registrationData.value.copyWith(
            userId: tempUserId,
            email: tempEmail,
            roleId: storage.read('TEMP_ROLE_ID') as String?,
            isOfficer: storage.read('IS_OFFICER') as bool? ?? false,
            profileStatus: 'incomplete',
          );

          userMetadata.value = UserMetadataModel(
            userId: tempUserId,
            email: tempEmail,
            roleId: storage.read('TEMP_ROLE_ID') as String?,
            isOfficer: storage.read('IS_OFFICER') as bool? ?? false,
            profileStatus: 'incomplete',
          );
        }
      }

      _completeInitialization();
    } catch (e) {
      Logger().e('Error handling no active session: $e');
    }
  }

  /// Complete initialization without triggering redirects
  Future<void> _completeInitialization() async {
    try {
      if (registrationData.value.roleId?.isNotEmpty == true) {
        await _setRoleFromMetadata();
      }
    } catch (e) {
      Logger().e('Error completing initialization: $e');
    }
  }

  /// Set role information from metadata
  Future<void> _setRoleFromMetadata() async {
    try {
      final roleId = registrationData.value.roleId;
      if (roleId == null) {
        TLoaders.errorSnackBar(
          title: 'Error',
          message: 'Role ID not found. Please contact support.',
        );
        return;
      }

      final role = await RolesRepository.instance.getRoleById(roleId);
      selectedRole.value = role;
    } catch (e) {
      Logger().e('Error setting role from metadata: $e');
    }
  }

  void _initializeControllers() {
    final isOfficer =
        AuthenticationRepository.instance.authUser?.userMetadata?['is_officer']
            as bool? ??
        false;

    Logger().d('Initializing controllers with isOfficer: $isOfficer');

    // Clear existing controllers first to prevent duplicates
    _clearExistingControllers();

    formKey = GlobalKey<FormState>();

    // Initialize controllers in order WITHOUT any cross-dependencies during initialization
    _createControllers(isOfficer);

    // Assign controller references
    _assignControllerReferences(isOfficer);

    // Set up data passing between controllers AFTER all controllers are created
    // Use a microtask to ensure all controllers are fully initialized
    Future.microtask(() {
      _setupDataPassing();
    });
  }

  void _clearExistingControllers() {
    if (Get.isRegistered<PersonalInfoController>()) {
      Get.delete<PersonalInfoController>(force: true);
    }
    if (Get.isRegistered<IdCardVerificationController>()) {
      Get.delete<IdCardVerificationController>(force: true);
    }
    if (Get.isRegistered<SelfieVerificationController>()) {
      Get.delete<SelfieVerificationController>(force: true);
    }
    if (Get.isRegistered<FaceLivenessController>()) {
      Get.delete<FaceLivenessController>(force: true);
    }
    if (Get.isRegistered<IdentityVerificationController>()) {
      Get.delete<IdentityVerificationController>(force: true);
    }
    if (Get.isRegistered<OfficerInfoController>()) {
      Get.delete<OfficerInfoController>(force: true);
    }
    if (Get.isRegistered<UnitInfoController>()) {
      Get.delete<UnitInfoController>(force: true);
    }
  }

  void _createControllers(bool isOfficer) {
    // Create controllers in isolation without any dependencies
    Get.put<PersonalInfoController>(PersonalInfoController(), permanent: false);

    Get.put<IdCardVerificationController>(
      IdCardVerificationController(isOfficer: isOfficer),
      permanent: false,
    );

    Get.put<SelfieVerificationController>(
      SelfieVerificationController(),
      permanent: false,
    );

    Get.put<IdentityVerificationController>(
      IdentityVerificationController(
        isOfficer: isOfficer,
        extractedIdCardNumber: '',
        extractedName: '',
      ),
      permanent: false,
    );

    if (isOfficer) {
      Get.put<OfficerInfoController>(OfficerInfoController(), permanent: false);
      Get.put<UnitInfoController>(UnitInfoController(), permanent: false);
    }
  }

  void _assignControllerReferences(bool isOfficer) {
    // Assign controller references
    personalInfoController = Get.find<PersonalInfoController>();
    idCardVerificationController = Get.find<IdCardVerificationController>();
    selfieVerificationController = Get.find<SelfieVerificationController>();
    identityController = Get.find<IdentityVerificationController>();

    if (isOfficer) {
      officerInfoController = Get.find<OfficerInfoController>();
      unitInfoController = Get.find<UnitInfoController>();
    } else {
      officerInfoController = null;
      unitInfoController = null;
    }
  }

  // Add new method to handle data passing between controllers
  void _setupDataPassing() {
    try {
      // Ensure all controllers are available before setting up listeners
      if (!Get.isRegistered<PersonalInfoController>() ||
          !Get.isRegistered<IdCardVerificationController>() ||
          !Get.isRegistered<SelfieVerificationController>() ||
          !Get.isRegistered<IdentityVerificationController>()) {
        Logger().w(
          'Not all controllers are registered, skipping data passing setup',
        );
        return;
      }

      // Listen to ID card verification changes and update registration data
      ever(idCardVerificationController.ktpModel, (model) {
        if (model != null) {
          _updateRegistrationDataFromIdCard();
        }
      });

      ever(idCardVerificationController.ktaModel, (model) {
        if (model != null) {
          _updateRegistrationDataFromIdCard();
        }
      });

      // Listen to personal info changes
      _setupPersonalInfoListeners();

      // Listen to selfie verification changes
      _setupSelfieVerificationListeners();

      // Listen to identity verification changes
      _setupIdentityVerificationListeners();

      // Listen to officer info changes (if applicable)
      if (registrationData.value.isOfficer) {
        _setupOfficerInfoListeners();
      }

      Logger().d('Data passing setup completed successfully');
    } catch (e) {
      Logger().e('Error setting up data passing: $e');
    }
  }

  void _setupPersonalInfoListeners() {
    try {
      // Update registration data when personal info changes
      personalInfoController.firstNameController.addListener(() {
        _updatePersonalInfoInRegistrationData();
      });
      personalInfoController.lastNameController.addListener(() {
        _updatePersonalInfoInRegistrationData();
      });
      personalInfoController.nameController.addListener(() {
        _updatePersonalInfoInRegistrationData();
      });
      personalInfoController.phoneController.addListener(() {
        _updatePersonalInfoInRegistrationData();
      });
      personalInfoController.addressController.addListener(() {
        _updatePersonalInfoInRegistrationData();
      });
    } catch (e) {
      Logger().e('Error setting up personal info listeners: $e');
    }
  }

  void _setupSelfieVerificationListeners() {
    try {
      ever(selfieVerificationController.isSelfieValid, (_) {
        _updateSelfieVerificationInRegistrationData();
      });
      ever(selfieVerificationController.isMatchWithIDCard, (_) {
        _updateSelfieVerificationInRegistrationData();
      });
      ever(selfieVerificationController.hasConfirmedSelfie, (_) {
        _updateSelfieVerificationInRegistrationData();
      });
    } catch (e) {
      Logger().e('Error setting up selfie verification listeners: $e');
    }
  }

  void _setupIdentityVerificationListeners() {
    try {
      identityController.nikController.addListener(() {
        _updateIdentityVerificationInRegistrationData();
      });
      identityController.fullNameController.addListener(() {
        _updateIdentityVerificationInRegistrationData();
      });
      identityController.placeOfBirthController.addListener(() {
        _updateIdentityVerificationInRegistrationData();
      });
      identityController.birthDateController.addListener(() {
        _updateIdentityVerificationInRegistrationData();
      });
      identityController.addressController.addListener(() {
        _updateIdentityVerificationInRegistrationData();
      });
    } catch (e) {
      Logger().e('Error setting up identity verification listeners: $e');
    }
  }

  void _setupOfficerInfoListeners() {
    try {
      if (officerInfoController != null) {
        officerInfoController!.nrpController.addListener(() {
          _updateOfficerInfoInRegistrationData();
        });
        officerInfoController!.rankController.addListener(() {
          _updateOfficerInfoInRegistrationData();
        });
      }

      if (unitInfoController != null) {
        unitInfoController!.unitIdController.addListener(() {
          _updateUnitInfoInRegistrationData();
        });
        unitInfoController!.positionController.addListener(() {
          _updateUnitInfoInRegistrationData();
        });
      }
    } catch (e) {
      Logger().e('Error setting up officer info listeners: $e');
    }
  }

  // Update methods for registration data
  void _updatePersonalInfoInRegistrationData() {
    registrationData.value = registrationData.value.copyWith(
      personalInfo: PersonalInfoData(
        firstName: personalInfoController.firstNameController.text,
        lastName: personalInfoController.lastNameController.text,
        fullName: personalInfoController.nameController.text,
        phone: personalInfoController.phoneController.text,
        address: personalInfoController.addressController.text,
      ),
    );
  }

  void _updateRegistrationDataFromIdCard() {
    registrationData.value = registrationData.value.copyWith(
      idCardVerification: IdCardVerificationData(
        imagePath: idCardVerificationController.idCardImage.value?.path,
        isValid: idCardVerificationController.isIdCardValid.value,
        isConfirmed: idCardVerificationController.hasConfirmedIdCard.value,
        validationMessage:
            idCardVerificationController.idCardValidationMessage.value,
        extractedInfo: Map<String, String>.from(
          idCardVerificationController.extractedInfo,
        ),
        ktpModel: idCardVerificationController.ktpModel.value,
        ktaModel: idCardVerificationController.ktaModel.value,
        faceModel: idCardVerificationController.idCardFace.value,
      ),
    );

    // Update identity controller with extracted data
    _updateIdentityControllerWithIdCardData();
  }

  void _updateSelfieVerificationInRegistrationData() {
    registrationData.value = registrationData.value.copyWith(
      selfieVerification: SelfieVerificationData(
        imagePath: selfieVerificationController.selfieImage.value?.path,
        isSelfieValid: selfieVerificationController.isSelfieValid.value,
        isLivenessCheckPassed:
            selfieVerificationController.isLivenessCheckPassed.value,
        isMatchWithIDCard: selfieVerificationController.isMatchWithIDCard.value,
        isConfirmed: selfieVerificationController.hasConfirmedSelfie.value,
        matchConfidence: selfieVerificationController.matchConfidence.value,
      ),
    );
  }

  void _updateIdentityVerificationInRegistrationData() {
    registrationData.value = registrationData.value.copyWith(
      identityVerification: IdentityVerificationData(
        nik: identityController.nikController.text,
        fullName: identityController.fullNameController.text,
        placeOfBirth: identityController.placeOfBirthController.text,
        birthDate: identityController.birthDateController.text,
        gender: identityController.selectedGender.value ?? 'Male',
        address: identityController.addressController.text,
      ),
    );
  }

  void _updateOfficerInfoInRegistrationData() {
    if (officerInfoController != null) {
      registrationData.value = registrationData.value.copyWith(
        officerInfo: OfficerInfoData(
          nrp: officerInfoController!.nrpController.text,
          rank: officerInfoController!.rankController.text,
          name: personalInfoController.nameController.text,
        ),
      );
    }
  }

  void _updateUnitInfoInRegistrationData() {
    if (unitInfoController != null) {
      registrationData.value = registrationData.value.copyWith(
        unitInfo: UnitInfoData(
          unitId: unitInfoController!.unitIdController.text,
          position: unitInfoController!.positionController.text,
        ),
      );
    }
  }

  void _updateIdentityControllerWithIdCardData() {
    try {
      String extractedIdNumber = '';
      String extractedName = '';

      if (idCardVerificationController.ktpModel.value != null) {
        extractedIdNumber =
            idCardVerificationController.ktpModel.value?.nik ?? '';
        extractedName = idCardVerificationController.ktpModel.value?.name ?? '';
      } else if (idCardVerificationController.ktaModel.value != null) {
        extractedIdNumber =
            idCardVerificationController.ktaModel.value?.nrp ?? '';
        extractedName = idCardVerificationController.ktaModel.value?.name ?? '';
      }

      // Only update if identity controller is properly initialized
      if (Get.isRegistered<IdentityVerificationController>()) {
        identityController.updateExtractedData(
          extractedIdNumber,
          extractedName,
        );
      }
    } catch (e) {
      Logger().e('Error updating identity controller with ID card data: $e');
    }
  }

  // Get step titles based on role
  List<String> getStepTitles() {
    if (selectedRole.value?.isOfficer ?? false) {
      // Officer steps - no personal info
      return ['ID Card', 'Selfie', 'Officer Info'];
    } else {
      // Viewer steps - includes personal info
      return ['Personal Info', 'ID Card', 'Selfie', 'Verify'];
    }
  }

  // Navigate to the next step
  void nextStep() async {
    // Validate the current form first
    if (formKey?.currentState?.validate() ?? false) {
      // If this is the last step, submit the form
      if (currentStep.value == totalSteps - 1) {
        await submitRegistration();
      } else {
        // Otherwise, go to the next step
        currentStep.value++;
      }
    }
  }

  // Navigate to the previous step
  void previousStep() {
    if (currentStep.value > 0) {
      currentStep.value--;
    }
  }

  // Go to a specific step
  void goToStep(int step) {
    if (step >= 0 && step < totalSteps) {
      currentStep.value = step;
    }
  }

  // Submit registration data
  Future<bool> submitRegistration() async {
    isLoading.value = true;

    try {
      // Your registration submission logic here
      await Future.delayed(const Duration(seconds: 2)); // Simulate API call

      // Handle successful registration
      isLoading.value = false;
      // Navigate to success page or home page

      return true;
    } catch (e) {
      isLoading.value = false;
      // Handle error
      return false;
    }
  }

  // Update officer information
  // void updateOfficerRegistrationData() async {
  //   try {
  //     isSubmitting.value = true;
  //     submitMessage.value = 'Submitting officer registration...';

  //     final isConnected = await NetworkManager.instance.isConnected();
  //     if (!isConnected) {
  //       TLoaders.errorSnackBar(
  //         title: 'No Internet Connection',
  //         message: 'Please check your internet connection and try again.',
  //       );
  //       isSubmitting.value = false;
  //       return;
  //     }

  //     // Get user ID and other key information
  //     final userId = AuthenticationRepository.instance.authUser!.id;
  //     final email = AuthenticationRepository.instance.authUser!.email;
  //     final roleId =
  //         AuthenticationRepository.instance.authUser!.userMetadata?['role_id']
  //             as String? ??
  //         '';

  //     // Create officer model
  //     final officer = OfficerModel(
  //       id: userId,
  //       unitId: unitInfoController?.unitIdController.text ?? '',
  //       roleId: roleId,
  //       nrp: officerInfoController?.nrpController.text ?? '',
  //       name:
  //           '${personalInfoController.firstNameController.text} ${personalInfoController.lastNameController.text}',
  //       rank: officerInfoController?.rankController.text,
  //       position: unitInfoController?.positionController.text,
  //       phone: personalInfoController.phoneController.text,
  //       email: email,
  //       placeOfBirth: identityController.placeOfBirthController.text,
  //       dateOfBirth: _parseBirthDate(
  //         identityController.birthDateController.text,
  //       ),
  //     );

  //     // Prepare auth metadata update
  //     final authMetadata = {
  //       'profile_status': 'completed',
  //       'is_officer': true,
  //       'name': officer.name,
  //       'nrp': officer.nrp,
  //       'unit_id': officer.unitId,
  //       'unit_name': _getUnitNameFromId(officer.unitId),
  //     };

  //     // Perform updates in a specific order:

  //     // 1. Update auth metadata
  //     try {
  //       await UserRepository.instance.updateUserMetadata(
  //         authMetadata,
  //       );
  //       Logger().d('Officer auth metadata updated successfully');
  //     } catch (e) {
  //       Logger().e('Error updating officer auth metadata: $e');
  //       throw Exception('Failed to update officer auth metadata: $e');
  //     }

  //     // 2. Update or create officer record
  //     try {
  //       await OfficerRepository.instance.updateOrCreateOfficer(
  //         officer.toJson(),
  //       );
  //       Logger().d('Officer data updated successfully');
  //     } catch (e) {
  //       Logger().e('Error updating officer data: $e');
  //       throw Exception('Failed to update officer data: $e');
  //     }

  //     isSubmitSuccess.value = true;
  //     submitMessage.value = 'Officer registration completed successfully';
  //   } catch (e) {
  //     Logger().e('Error updating officer data: $e');
  //     isSubmitSuccess.value = false;
  //     submitMessage.value =
  //         'Failed to complete officer registration: ${e.toString()}';
  //   } finally {
  //     isSubmitting.value = false;
  //   }
  // }

  // Storing registration data to Supabase
  void updateUserRegistrationData() async {
    try {
      isSubmitting.value = true;

      // validate all controllers before proceeding
      // if (!formKey!.currentState!.validate()) {
      //   TLoaders.errorSnackBar(
      //     title: 'Validation Error',
      //     message: 'Please fill in all required fields correctly.',
      //   );
      //   isSubmitting.value = false;
      //   submitMessage.value = 'Please fill in all required fields correctly.';
      //   return;
      // }

      final isConnected = await NetworkManager.instance.isConnected();
      if (!isConnected) {
        TLoaders.errorSnackBar(
          title: 'No Internet Connection',
          message: 'Please check your internet connection and try again.',
        );
        isSubmitting.value = false;
        submitMessage.value =
            'Failed to complete registration: No internet connection';
        return;
      }

      final currentUser = await UserRepository.instance.getUserById(
        AuthenticationRepository.instance.authUser!.id,
      );

      final updateUser = currentUser.copyWith(
        phone: personalInfoController.phoneController.text,
        updatedAt: DateTime.now(),
      );

      final updateProfile = currentUser.profile?.copyWith(
        nik: identityController.nikController.text,
        firstName: personalInfoController.firstNameController.text,
        lastName: personalInfoController.lastNameController.text,
        address: {
          'full_address': personalInfoController.addressController.text,
        },
        placeOfBirth: identityController.placeOfBirthController.text,
        birthDate: _parseBirthDate(identityController.birthDateController.text),
      );

      // Check if NIK is already registered (but ignore if it's the current user's NIK)
      final isNikTaken = await UserRepository.instance.isNikExists(
        updateProfile!.nik!,
      );

      if (isNikTaken) {
        TLoaders.errorSnackBar(
          title: 'Error',
          message: 'NIK already registered to another user!',
        );
        isSubmitting.value = false;
        submitMessage.value = 'NIK already registered to another user!';
        return;
      }

      // Update user model in database
      final userRepository = UserRepository.instance;
      final profileRepository = ProfileRepository.instance;

      final userUpdated = await userRepository.updateUser(updateUser);
      await profileRepository.updateProfile(updateProfile);

      if (userUpdated == null) {
        TLoaders.errorSnackBar(
          title: 'Error',
          message: 'Failed to update user profile. Please try again.',
        );
        isSubmitting.value = false;
        submitMessage.value =
            'Failed to update user profile. Please try again.';
        return;
      }

      // Update metadata first
      await userRepository.updateProfileStatus('completed');

      Logger().d('User metadata updated successfully');

      isSubmitSuccess.value = true;
      // submitMessage.value = 'Registration completed successfully';

      Get.off(
        () => StateScreen(
          title: 'Registration Completed',
          subtitle: 'Your registration has been successfully completed.',
          image: TImages.womanHuggingEarth,
          isSvg: true,
          showButton: true,
          primaryButtonTitle: 'Back to sign in',
          onPressed: () => AuthenticationRepository.instance.screenRedirect(),
        ),
      );
    } catch (e) {
      Logger().e('Error updating registration data: $e');
      isSubmitSuccess.value = false;
      submitMessage.value = 'Failed to complete registration: ${e.toString()}';
      TLoaders.errorSnackBar(
        title: 'Error',
        message: 'Failed to complete registration: ${e.toString()}',
      );
    } finally {
      isSubmitting.value = false;
    }
  }

  /// Save registration data using the centralized model
  Future<bool> saveRegistrationData({Map<String, dynamic>? summaryData}) async {
    try {
      Logger().d('Starting registration data save process');

      // Ensure all current form data is captured in registration data
      _updatePersonalInfoInRegistrationData();
      _updateRegistrationDataFromIdCard();
      _updateSelfieVerificationInRegistrationData();
      _updateIdentityVerificationInRegistrationData();

      if (registrationData.value.isOfficer) {
        _updateOfficerInfoInRegistrationData();
        _updateUnitInfoInRegistrationData();
      }

      // Create final data from registration model
      Map<String, dynamic> finalData = registrationData.value.toJson();

      Logger().d('Registration data prepared and ready for submission');

      final userRepo = Get.find<UserRepository>();
      final result = await userRepo.updateUserProfile(finalData);

      Logger().d('Registration submission result: $result');
      return result;
    } catch (e) {
      Logger().e('Error saving registration data: $e');
      return false;
    }
  }

  // Legacy methods for backward compatibility
  void collectAllFormData() {
    // This is now handled automatically by the listeners
    _updatePersonalInfoInRegistrationData();
    _updateRegistrationDataFromIdCard();
    _updateSelfieVerificationInRegistrationData();
    _updateIdentityVerificationInRegistrationData();

    if (registrationData.value.isOfficer) {
      _updateOfficerInfoInRegistrationData();
      _updateUnitInfoInRegistrationData();
    }
  }

  DateTime? _parseBirthDate(String dateStr) {
    try {
      if (dateStr.isEmpty) return null;

      if (dateStr.contains('-')) {
        return DateTime.parse(dateStr);
      }

      if (dateStr.contains('/')) {
        final parts = dateStr.split('/');
        if (parts.length == 3) {
          final day = int.parse(parts[0]);
          final month = int.parse(parts[1]);
          final year = int.parse(parts[2]);
          return DateTime(year, month, day);
        }
      }

      return null;
    } catch (e) {
      return null;
    }
  }
}
