import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:get_it/get_it.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/cache_consts.dart';
import 'package:hmg_patient_app_new/core/common_models/nationality_country_model.dart';
import 'package:hmg_patient_app_new/core/common_models/privilege/HMCProjectListModel.dart';
import 'package:hmg_patient_app_new/core/common_models/privilege/ProjectDetailListModel.dart';
import 'package:hmg_patient_app_new/core/common_models/privilege/VidaPlusProjectListModel.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/core/utils/request_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/core/utils/validation_utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/features/authentication/authentication_repo.dart';
import 'package:hmg_patient_app_new/features/authentication/models/request_models/check_activation_code_register_request_model.dart';
import 'package:hmg_patient_app_new/features/authentication/models/request_models/registration_payload_model.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/authenticated_user_resp_model.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/check_activation_code_resp_model.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/check_user_staus_nhic_response_model.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/select_device_by_imei.dart';
import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/authentication/login.dart';
import 'package:hmg_patient_app_new/presentation/authentication/saved_login_screen.dart';
import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart';
import 'package:hmg_patient_app_new/presentation/my_family/my_family.dart';
import 'package:hmg_patient_app_new/routes/app_routes.dart';
import 'package:hmg_patient_app_new/services/cache_service.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';
import 'package:hmg_patient_app_new/services/localauth_service.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/core/services/turnstile_service.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_calendar_model.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:sms_otp_auto_verify/sms_otp_auto_verify.dart';

import '../insurance/insurance_view_model.dart';
import '../profile_settings/profile_settings_repo.dart';
import 'models/request_models/get_user_mobile_device_data.dart';
import 'models/request_models/insert_patient_mobile_deviceinfo.dart';
import 'models/request_models/patient_insert_device_imei_request.dart';

class AuthenticationViewModel extends ChangeNotifier {
  final AuthenticationRepo _authenticationRepo;
  final AppState _appState;
  final ErrorHandlerService _errorHandlerService;
  final DialogService _dialogService;
  final NavigationService _navigationService;
  final LocalAuthService _localAuthService;
  final TurnstileService _turnstileService;

  AuthenticationViewModel({
    required AppState appState,
    required AuthenticationRepo authenticationRepo,
    required ErrorHandlerService errorHandlerService,
    required DialogService dialogService,
    required NavigationService navigationService,
    required CacheService cacheService,
    required LocalAuthService localAuthService,
    required TurnstileService turnstileService,
  })  : _navigationService = navigationService,
        _dialogService = dialogService,
        _errorHandlerService = errorHandlerService,
        _appState = appState,
        _authenticationRepo = authenticationRepo,
        _localAuthService = localAuthService,
        _turnstileService = turnstileService {}
  final TextEditingController nationalIdController = TextEditingController(),
      phoneNumberController = TextEditingController(),
      dobController = TextEditingController(),
      nameController = TextEditingController(),
      emailController = TextEditingController();

  CountryEnum selectedCountrySignup = CountryEnum.saudiArabia;
  MaritalStatusTypeEnum? maritalStatus;
  GenderTypeEnum? genderType;
  bool isTermsAccepted = false;
  List<NationalityCountries>? countriesList;
  String? dob = "";
  final CacheService cacheService = GetIt.instance<CacheService>();

  NationalityCountries? pickedCountryByUAEUser;
  CalenderEnum calenderType = CalenderEnum.gregorian;
  LoginTypeEnum loginTypeEnum = LoginTypeEnum.sms;

  final ValueNotifier<bool> otpScreenNotifier = ValueNotifier<bool>(false);
  int patientShareRequestID = 0;

  //================== Validation Error States ==================

  // Login screen errors
  String? _nationalIdError;

  String? get nationalIdError => _nationalIdError;

  // Phone number errors (used in multiple screens)
  String? _phoneNumberError;

  String? get phoneNumberError => _phoneNumberError;

  // Registration screen errors
  String? _nameError;

  String? get nameError => _nameError;

  String? _emailError;

  String? get emailError => _emailError;

  String? _dobError;

  String? get dobError => _dobError;

  // Check if registration form has any errors (for container border)
  bool get hasRegistrationFormError => _nationalIdError != null || _dobError != null;

  // Check if ID and phone have errors (for family file container)
  bool get hasIdAndPhoneError => _nationalIdError != null || _phoneNumberError != null;

  // Additional field errors for UAE registration step 2
  String? _genderError;
  String? _maritalStatusError;
  String? _countryError;

  // Getters for step 2 field errors (nameError and emailError already exist above)
  String? get genderError => _genderError;

  String? get maritalStatusError => _maritalStatusError;

  String? get countryError => _countryError;

  // Check if registration step 2 form has any errors (for container border)
  bool get hasRegistrationStep2FormError => _nameError != null || _genderError != null || _maritalStatusError != null || _countryError != null;

  // Clear all step 2 field errors
  void clearAllStep2FieldErrors() {
    _nameError = null;
    _genderError = null;
    _maritalStatusError = null;
    _countryError = null;
    _emailError = null;
    notifyListeners();
  }

  // Clear gender error
  void clearGenderError() {
    _genderError = null;
    notifyListeners();
  }

  // Clear marital status error
  void clearMaritalStatusError() {
    _maritalStatusError = null;
    notifyListeners();
  }

  // Clear country error
  void clearCountryError() {
    _countryError = null;
    notifyListeners();
  }

  //==================

  String errorMsg = '';
  final FocusNode myFocusNode = FocusNode();
  var healthId;
  int getDeviceLastLogin = 1;

  bool isInitialLoginNavigated = false;

  Future<void> onLoginPressed() async {
    setIsInitialLoginNavigated(false);
    try {
      LoaderBottomSheet.showLoader();
      //TODO:  We will remove this delay
      // await Future.delayed(Duration(seconds: 3));
      var data = _appState.getSelectDeviceByImeiRespModelElement;
      log("Cached IMEI data: ${data?.toJson()}");
      if (data != null) {
        await _handleExistingImeiData(data);
      } else {
        await handleNewImeiRegistration();
      }
    } catch (e) {
      log("Error in onLoginPressed: $e");
      LoaderBottomSheet.hideLoader();
      _dialogService.showErrorBottomSheet(message: "An unexpected error occurred. Please try again.", onOkPressed: () {});
    }
  }

  Future<void> clearDefaultInputValues() async {
    nationalIdController.clear();
    phoneNumberController.clear();
    emailController.clear();
    dobController.clear();
    maritalStatus = null;
    genderType = null;
    isTermsAccepted = false;
    selectedCountrySignup = CountryEnum.saudiArabia;
    pickedCountryByUAEUser = null;
    _appState.setUserRegistrationPayload = RegistrationDataModelPayload();
    _appState.setNHICUserData = CheckUserStatusResponseNHIC();
    getIt.get<SymptomsCheckerViewModel>().setSelectedHeight(0);
    getIt.get<SymptomsCheckerViewModel>().setSelectedWeight(0);

    // Clear all validation errors
    clearAllErrors();
  }

  //==================== Validation Methods ====================

  /// Clear all validation errors
  void clearAllErrors() {
    _nationalIdError = null;
    _phoneNumberError = null;
    _nameError = null;
    _emailError = null;
    _dobError = null;
    notifyListeners();
  }

  /// Clear national ID error
  void clearNationalIdError() {
    _nationalIdError = null;
    notifyListeners();
  }

  /// Clear phone number error
  void clearPhoneNumberError() {
    _phoneNumberError = null;
    notifyListeners();
  }

  /// Clear name error
  void clearNameError() {
    _nameError = null;
    notifyListeners();
  }

  /// Clear email error
  void clearEmailError() {
    _emailError = null;
    notifyListeners();
  }

  /// Clear DOB error
  void clearDobError() {
    _dobError = null;
    notifyListeners();
  }

  /// Validate National ID for login/registration
  /// Returns true if valid, false otherwise
  /// Only shows red border error, no dialog popups
  bool validateNationalId() {
    // Clear previous error
    _nationalIdError = null;

    // Check if field is empty
    if (nationalIdController.text.isEmpty) {
      _nationalIdError = LocaleKeys.pleaseEnterAnationalID.tr();
      notifyListeners();
      return false;
    }

    // Check if it's 10 digits and valid Saudi ID
    String cleanedId = nationalIdController.text.replaceAll(RegExp(r'[^0-9]'), '');
    if (cleanedId.length == 10) {
      if (!Utils.isSAUDIIDValid(cleanedId)) {
        _nationalIdError = LocaleKeys.enterValidNationalId.tr();
        notifyListeners();
        return false;
      }
    }

    // Validate based on selected country
    if (selectedCountrySignup == CountryEnum.saudiArabia) {
      if (cleanedId.length == 10) {
        if (!ValidationUtils.validateIqama(nationalIdController.text)) {
          _nationalIdError = LocaleKeys.pleaseEnterAValidIqamaID.tr();
          notifyListeners();
          return false;
        }
      } else {
        return true;
      }
    } else if (selectedCountrySignup == CountryEnum.unitedArabEmirates) {
      if (!ValidationUtils.validateUaeNationalId(nationalIdController.text)) {
        _nationalIdError = LocaleKeys.pleaseEnterAValidNationalID.tr();
        notifyListeners();
        return false;
      }
    }

    // Clear error on success
    _nationalIdError = null;
    notifyListeners();
    return true;
  }

  /// Validate phone number
  /// Returns true if valid, false otherwise
  /// Only shows red border error, no dialog popups
  bool validatePhoneNumber() {
    // Clear previous error
    _phoneNumberError = null;

    // Check if phone is empty
    if (phoneNumberController.text.isEmpty) {
      _phoneNumberError = LocaleKeys.enterValidPhoneNumber.tr();
      notifyListeners();
      return false;
    }

    // Check if "Others" country is selected and phone number starts with restricted codes
    if (selectedCountrySignup == CountryEnum.others) {
      if (phoneNumberController.text.startsWith('00966') || phoneNumberController.text.startsWith('00971')) {
        _phoneNumberError = LocaleKeys.cannotEnterSaudiOrUAENumber.tr();
        notifyListeners();
        return false;
      }
    }

    // Clear error on success
    _phoneNumberError = null;
    notifyListeners();
    return true;
  }

  /// Validate National ID and Phone Number together
  /// Returns true if both are valid, false otherwise
  /// Only shows red border errors, no dialog popups
  /// Uses PROGRESSIVE VALIDATION - shows errors step by step
  bool validateIdAndPhone() {
    // Clear all previous errors first
    _nationalIdError = null;
    _phoneNumberError = null;

    // Step 1: Validate National ID empty first (highest priority)
    if (nationalIdController.text.isEmpty) {
      _nationalIdError = LocaleKeys.pleaseEnterAnationalID.tr();
      notifyListeners();
      return false; // Stop here, don't check phone yet
    }

    // Step 2: Validate National ID format
    String cleanedId = nationalIdController.text.replaceAll(RegExp(r'[^0-9]'), '');

    if (cleanedId.length == 10) {
      if (!Utils.isSAUDIIDValid(cleanedId)) {
        _nationalIdError = LocaleKeys.enterValidNationalId.tr();
        notifyListeners();
        return false; // Stop here
      }
    }

    // Step 3: Validate National ID based on country
    if (selectedCountrySignup == CountryEnum.saudiArabia) {
      if (!ValidationUtils.validateIqama(nationalIdController.text)) {
        _nationalIdError = LocaleKeys.pleaseEnterAValidIqamaID.tr();
        notifyListeners();
        return false; // Stop here
      }
    } else if (selectedCountrySignup == CountryEnum.unitedArabEmirates) {
      if (!ValidationUtils.validateUaeNationalId(nationalIdController.text)) {
        _nationalIdError = LocaleKeys.pleaseEnterAValidNationalID.tr();
        notifyListeners();
        return false; // Stop here
      }
    }

    // Step 4: ONLY validate phone if National ID is fully valid
    if (phoneNumberController.text.isEmpty) {
      _phoneNumberError = LocaleKeys.enterValidPhoneNumber.tr();
      notifyListeners();
      return false; // Stop here
    }

    // Step 5: Validate phone number format based on country
    if (selectedCountrySignup == CountryEnum.others) {
      if (phoneNumberController.text.startsWith('00966') || phoneNumberController.text.startsWith('00971')) {
        _phoneNumberError = LocaleKeys.cannotEnterSaudiOrUAENumber.tr();
        notifyListeners();
        return false;
      }
    }

    // All validations passed
    notifyListeners();
    return true;
  }

  /// Validate registration form (National ID, DOB, Terms)
  /// Returns true if all valid, false otherwise
  /// Only shows red border errors, no dialog popups
  /// Uses PROGRESSIVE VALIDATION - shows errors step by step
  bool validateRegistrationForm() {
    // Clear all previous errors first
    _nationalIdError = null;
    _dobError = null;

    // Step 1: Validate National ID first (highest priority)
    if (nationalIdController.text.isEmpty) {
      _nationalIdError = LocaleKeys.pleaseEnterAnationalID.tr();
      notifyListeners();
      return false; // Stop here, don't check other fields
    }

    // Step 2: Validate National ID format
    String cleanedId = nationalIdController.text.replaceAll(RegExp(r'[^0-9]'), '');

    if (cleanedId.length == 10) {
      if (!Utils.isSAUDIIDValid(cleanedId)) {
        _nationalIdError = LocaleKeys.enterValidNationalId.tr();
        notifyListeners();
        return false; // Stop here
      }
    }

    // Step 3: Validate based on selected country
    if (selectedCountrySignup == CountryEnum.saudiArabia) {
      if (!ValidationUtils.validateIqama(nationalIdController.text)) {
        _nationalIdError = LocaleKeys.pleaseEnterAValidIqamaID.tr();
        notifyListeners();
        return false; // Stop here
      }
    } else if (selectedCountrySignup == CountryEnum.unitedArabEmirates) {
      if (!ValidationUtils.validateUaeNationalId(nationalIdController.text)) {
        _nationalIdError = LocaleKeys.pleaseEnterAValidNationalID.tr();
        notifyListeners();
        return false; // Stop here
      }
    }

    // Step 4: Only validate DOB if National ID is valid
    if (dobController.text.isEmpty || dob == null || dob!.isEmpty) {
      _dobError = LocaleKeys.pleaseEnterAValidDateOfBirth.tr();
      notifyListeners();
      return false; // Stop here
    }

    // Step 5: Only validate Terms if both National ID and DOB are valid
    // Show dialog popup for Terms (old behavior)
    if (!isTermsAccepted) {
      _dialogService.showExceptionBottomSheet(
        message: LocaleKeys.pleaseAcceptTermsConditions.tr(),
        onOkPressed: () {
          _navigationService.pop();
        },
      );
      notifyListeners();
      return false; // Stop here
    }

    // All validations passed
    notifyListeners();
    return true;
  }

  //==================== End Validation Methods ====================

  /// Validate registration step 2 form (UAE users: name, gender, marital status, country)
  /// Returns true if all valid, false otherwise
  /// Shows only the FIRST error encountered - progressive validation
  bool validateRegistrationStep2Form() {
    final isArabic = _appState.isArabic();

    // Clear all previous errors first
    _nameError = null;
    _genderError = null;
    _maritalStatusError = null;
    _countryError = null;

    // Step 1: Validate name (only for UAE users)
    // if (isUserFromUAE()) {
    //   if (nameController.text.trim().isEmpty) {
    //     _nameError = isArabic ? "الرجاء إدخال الاسم الكامل" : "Please enter full name";
    //     notifyListeners();
    //     return false; // Stop here
    //   }
    // }

    if (isUserFromUAE()) {
      // Remove extra spaces between words
      final fullName = nameController.text.trim().replaceAll(RegExp(r'\s+'), ' ');

      // Split into words
      final nameParts = fullName.split(' ');

      // Require at least 2 words
      if (nameParts.length < 2) {
        _nameError = isArabic ? "الرجاء إدخال الاسم الكامل" : "Please enter full name";

        notifyListeners();
        return false;
      }
    }

    // Step 2: Validate gender (only for UAE users)
    if (isUserFromUAE()) {
      if (genderType == null) {
        _genderError = isArabic ? "الرجاء اختيار الجنس" : "Please select gender";
        notifyListeners();
        return false; // Stop here
      }
    }

    // Step 3: Validate marital status (only for UAE users)
    if (isUserFromUAE()) {
      if (maritalStatus == null) {
        _maritalStatusError = isArabic ? "الرجاء اختيار الحالة الاجتماعية" : "Please select marital status";
        notifyListeners();
        return false; // Stop here
      }
    }

    // Step 4: Validate country (only for UAE users)
    if (isUserFromUAE()) {
      if (pickedCountryByUAEUser == null) {
        _countryError = isArabic ? "الرجاء اختيار البلد" : "Please select country";
        notifyListeners();
        return false; // Stop here
      }
    }

    // All validations passed
    notifyListeners();
    return true;
  }

  /// Validate email in the bottom sheet
  /// Returns true if valid, false otherwise
  bool validateEmail() {
    final isArabic = _appState.isArabic();

    // Clear previous error
    _emailError = null;

    // Step 1: Check if email is empty
    if (emailController.text.trim().isEmpty) {
      _emailError = isArabic ? "الرجاء إدخال البريد الإلكتروني" : "Please enter email";
      notifyListeners();
      return false;
    }

    // Step 2: Validate email format
    final bool emailIsValid = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}$").hasMatch(emailController.text.trim());
    if (!emailIsValid) {
      _emailError = isArabic ? "الرجاء إدخال تنسيق بريد إلكتروني صالح" : "Please enter a valid email format";
      notifyListeners();
      return false;
    }

    // Email is valid
    notifyListeners();
    return true;
  }

  //==================== End Validation Methods ====================

  void onCountryChange(CountryEnum country) {
    selectedCountrySignup = country;
    notifyListeners();
  }

  void onCalenderTypeChange(bool isGregorian) {
    calenderType = isGregorian ? CalenderEnum.gregorian : CalenderEnum.hijri;
    notifyListeners();
  }

  void onDobChange(String? date) {
    if (date == null || date.isEmpty) {
      debugPrint('onDobChange: date is null or empty');
      return;
    }

    try {
      if (calenderType == CalenderEnum.hijri) {
        // Use DateRangCalenderModel for accurate Umm al-Qura conversion
        final calendarModel = DateRangCalenderModel(
          appState: _appState,
          navigationService: _errorHandlerService,
          dialogService: _dialogService,
        );

        // Parse the Gregorian date with validation
        DateTime gregorianDate;
        try {
          gregorianDate = DateTime.parse(date);
        } catch (parseError) {
          debugPrint('onDobChange: Failed to parse date "$date" - $parseError');
          // Try to handle common date format issues
          gregorianDate = _tryParseDateFlexibly(date);
        }

        // Convert to Hijri
        final hijriDate = calendarModel.gregorianToHijri(gregorianDate);

        // Validate Hijri date components
        if (hijriDate.year <= 0 || hijriDate.month <= 0 || hijriDate.day <= 0) {
          debugPrint('onDobChange: Invalid Hijri date components - Year: ${hijriDate.year}, Month: ${hijriDate.month}, Day: ${hijriDate.day}');
          return;
        }

        // Create DateTime from Hijri components for display
        final hijriDateTimeForController = DateTime(hijriDate.year, hijriDate.month, hijriDate.day);

        // Format for API (use original Gregorian date)
        dob = Utils.formatDateForApi(date);

        // Format for display (use Hijri)
        dobController.text = Utils.formatHijriDateToDisplay(hijriDateTimeForController.toIso8601String());
      } else {
        // Gregorian calendar mode
        // Validate the date can be parsed
        try {
          DateTime.parse(date);
        } catch (parseError) {
          debugPrint('onDobChange: Failed to parse date "$date" - $parseError');
          // Try flexible parsing to validate
          _tryParseDateFlexibly(date);
        }

        // Format for display
        dobController.text = Utils.formatDateToDisplay(date);

        // Format for API
        dob = Utils.formatDateForApi(date);
      }

      clearDobError();
      notifyListeners();
    } catch (e, stackTrace) {
      debugPrint('onDobChange: Unexpected error processing date "$date" - $e');
      debugPrint('Stack trace: $stackTrace');

      // Set error state if needed
      // You can add error handling UI feedback here
    }
  }

  /// Helper method to handle flexible date parsing for common formats
  DateTime _tryParseDateFlexibly(String dateString) {
    // Remove extra whitespace
    dateString = dateString.trim();

    // Try standard ISO format first
    try {
      return DateTime.parse(dateString);
    } catch (_) {}

    // Try common formats with regex
    final patterns = [
      RegExp(r'^(\d{4})-(\d{1,2})-(\d{1,2})$'), // yyyy-M-d or yyyy-MM-dd
      RegExp(r'^(\d{1,2})/(\d{1,2})/(\d{4})$'), // d/M/yyyy or dd/MM/yyyy
      RegExp(r'^(\d{4})/(\d{1,2})/(\d{1,2})$'), // yyyy/M/d or yyyy/MM/dd
    ];

    for (var pattern in patterns) {
      final match = pattern.firstMatch(dateString);
      if (match != null) {
        try {
          if (pattern.pattern.startsWith(r'^\d{4}')) {
            // Year first formats
            final year = int.parse(match.group(1)!);
            final month = int.parse(match.group(2)!);
            final day = int.parse(match.group(3)!);
            return DateTime(year, month, day);
          } else {
            // Day first formats
            final day = int.parse(match.group(1)!);
            final month = int.parse(match.group(2)!);
            final year = int.parse(match.group(3)!);
            return DateTime(year, month, day);
          }
        } catch (_) {}
      }
    }

    // If all else fails, throw descriptive error
    throw FormatException('Unable to parse date: "$dateString". Expected format: yyyy-MM-dd');
  }

  Future<void> loadCountriesData() async {
    final String response = await rootBundle.loadString('assets/json/countriesList.json');
    final List<dynamic> data = json.decode(response);
    countriesList = data.map((e) => NationalityCountries.fromJson(e)).toList();
  }

  void onMaritalStatusChange(String? status) {
    final newMaritalStatus = MaritalStatusTypeExtension.fromType(status);
    if (newMaritalStatus != null) {
      maritalStatus = newMaritalStatus;
      clearMaritalStatusError();
      notifyListeners();
    }
  }

  void onGenderChange(String? status) {
    final newGender = GenderTypeExtension.fromType(status);
    if (newGender != null) {
      genderType = newGender;
      clearGenderError();
      notifyListeners();
    }
  }

  void clearEmailInput() {
    emailController.text = "";
  }

  void onUAEUserCountrySelection(String? value) {
    pickedCountryByUAEUser = countriesList!.firstWhere((element) => element.name == value || element.nameN == value);
    clearCountryError();
    notifyListeners();
  }

  void onPhoneNumberChange(String? phoneNumber) {
    phoneNumberController.text = phoneNumber!;

    // Real-time validation for Others country - prevent entering Saudi/UAE numbers
    if (selectedCountrySignup == CountryEnum.others) {
      if (phoneNumber.startsWith('00966') || phoneNumber.startsWith('00971')) {
        // Remove the restricted prefix
        phoneNumberController.text = phoneNumber.replaceAll(RegExp(r'^(00966|00971)'), '');
        phoneNumberController.selection = TextSelection.fromPosition(
          TextPosition(offset: phoneNumberController.text.length),
        );
      }
    }
  }

  setIsInitialLoginNavigated(bool isInitialLoginNavigated) {
    this.isInitialLoginNavigated = isInitialLoginNavigated;
    notifyListeners();
  }

  void onTermAccepted() {
    isTermsAccepted = !isTermsAccepted;
    notifyListeners();
  }

  bool isUserFromUAE() {
    bool isFromUAE = false;
    if (_appState.getUserRegistrationPayload.patientOutSa != 0) {
      isFromUAE = true;
    }
    return isFromUAE;
  }

  void savePushTokenToAppState() async {
    _appState.deviceToken = await Utils.getStringFromPrefs(CacheConst.pushToken);
  }

  Future<void> selectDeviceImei({bool isNavigate = true, required Function(dynamic data) onSuccess, Function(String)? onError}) async {
    // LoadingUtils.showFullScreenLoading();
    // String firebaseToken = _appState.deviceToken;
    String firebaseToken = await Utils.getStringFromPrefs(CacheConst.pushToken);
    // String firebaseToken = "fY1fq_cITMmUCztA3UKKL9:APA91bEb2ZcdCPQPq3QsA0NW6a6btFvN-JjB1Pn3ZCoCzBMmVUhhh1ZQMtRn9tYPQ5G-jHDLiEpVAlBuRCVMkLDxa-zijsqbIui-4A-ynwclDWGFT4bUHTc";
    // == ""
    // ? "dOGRRszQQMGe_9wA5Hx3kO:APA91bFV5IcIJXvcCXXk0tc2ddtZgWwCPq7sGSuPr-YW7iiJpQZKgFGN9GAzCVOWL8MfheaP1slE8MdxB7lczdPBGdONQ7WbMmhgHcsUCUktq-hsapGXXqc"
    // : _appState.deviceToken;
    final result = await _authenticationRepo.selectDeviceByImei(firebaseToken: firebaseToken);

    result.fold(
      (failure) async {
        // LoadingUtils.hideFullScreenLoader();
        // await _errorHandlerService.handleError(failure: failure);
        LoaderBottomSheet.hideLoader();
        if (isNavigate) {
          _navigationService.pushPage(page: LoginScreen());
        }
      },
      (apiResponse) {
        // LoadingUtils.hideFullScreenLoader();
        log("apiResponse: ${apiResponse.data?.toJson().toString()}");
        log("messageStatus: ${apiResponse.messageStatus.toString()}");
        if (apiResponse.messageStatus == 1) {
          onSuccess(apiResponse.data);
        } else if (apiResponse.messageStatus == 2) {
          _dialogService.showErrorBottomSheet(message: "Message Status = 2", onOkPressed: () {});
        }
      },
    );
  }

  Future<void> _handleExistingImeiData(dynamic data) async {
    try {
      SelectDeviceByImeiRespModelElement? savedData = _appState.getSelectDeviceByImeiRespModelElement;
      LoaderBottomSheet.hideLoader();

      if (savedData != null) {
        // TODO: Navigate to SavedLogin when available
        //_navigationService.pushPage(page: LoginScreen());
        _navigationService.pushPage(page: SavedLogin());
      }
    } catch (e) {
      log("Error handling existing IMEI data: $e");
      LoaderBottomSheet.hideLoader();
      _navigationService.pushPage(page: LoginScreen());
    }
  }

  Future<void> handleNewImeiRegistration({bool isNavigate = true}) async {
    print("handleNewImeiRegistration called");
    await selectDeviceImei(
        isNavigate: isNavigate,
        onSuccess: (dynamic respData) async {
          try {
            if (respData != null) {
              dynamic data = await SelectDeviceByImeiRespModelElement.fromJson(respData.toJson());
              _appState.setSelectDeviceByImeiRespModelElement(data);
              LoaderBottomSheet.hideLoader();

              // TODO: Navigate to SavedLogin when available
              // SelectDeviceByImeiRespModelElement savedData =
              //     SelectDeviceByImeiRespModelElement.fromJson(respData);
              if (!isInitialLoginNavigated) {
                _navigationService.pushPage(page: SavedLogin());
              }
              // _navigationService.pushPage(page: LoginScreen());
            } else {
              if (isNavigate) {
                LoaderBottomSheet.hideLoader();
                _navigationService.pushPage(page: LoginScreen());
              }
            }
          } catch (e) {
            if (isNavigate) {
              log("Error processing IMEI registration response: $e");
              LoaderBottomSheet.hideLoader();
              _navigationService.pushPage(page: LoginScreen());
            }
          }
        },
        onError: (String error) {
          LoaderBottomSheet.hideLoader();
          _dialogService.showErrorBottomSheet(message: error, onOkPressed: () {});
        });
  }

  Future<void> checkUserAuthentication({required OTPTypeEnum otpTypeEnum, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    // TODO: THIS SHOULD BE REMOVED LATER ON AND PASSED FROM APP STATE DIRECTLY INTO API CLIENT. BECAUSE THIS API ONLY NEEDS FEW PARAMS FROM USER

    loginTypeEnum = otpTypeEnum == OTPTypeEnum.sms ? LoginTypeEnum.sms : LoginTypeEnum.whatsapp;

    // if (phoneNumberController.text.isEmpty) {
    //   phoneNumberController.text = "504278212";
    // }

    bool isValidated = ValidationUtils.isValidatePhoneAndId(phoneNumber: phoneNumberController.text, nationalId: nationalIdController.text);

    if (!isValidated) {
      return;
    }
    LoaderBottomSheet.showLoader();
    // LoadingUtils.showFullScreenLoader();

    dynamic checkPatientAuthenticationReq = RequestUtils.getPatientAuthenticationRequest(
        phoneNumber: phoneNumberController.text,
        nationId: nationalIdController.text,
        isForRegister: false,
        patientOutSA: false,
        // patientOutSA: selectedCountrySignup == CountryEnum.others
        //     ? false
        //     : (_appState.getSelectDeviceByImeiRespModelElement != null && _appState.getSelectDeviceByImeiRespModelElement!.outSa == true ? true : false),
        otpTypeEnum: otpTypeEnum,
        patientId: 0,
        zipCode: selectedCountrySignup == CountryEnum.others
            ? "0"
            : (_appState.getSelectDeviceByImeiRespModelElement != null && _appState.getSelectDeviceByImeiRespModelElement!.outSa == true
                ? CountryEnum.unitedArabEmirates.countryCode
                : selectedCountrySignup.countryCode),
        calenderType: calenderType);

    final result = await _authenticationRepo.checkPatientAuthentication(checkPatientAuthenticationReq: checkPatientAuthenticationReq);

    result.fold(
      (failure) async => await _errorHandlerService.handleError(
          failure: failure,
          onUnHandledFailure: (failure) async {
            LoaderBottomSheet.hideLoader();
            await _dialogService.showCommonBottomSheetWithoutH(
                message: failure.message,
                label: LocaleKeys.notice.tr(),
                onOkPressed: () {
                  _navigationService.pushAndReplace(AppRoutes.register);
                },
                onCancelPressed: () {
                  _navigationService.pop();
                });
          }),
      (apiResponse) async {
        if (apiResponse.messageStatus == 2) {
          LoaderBottomSheet.hideLoader();
          await _dialogService.showErrorBottomSheet(message: apiResponse.errorMessage ?? "ErrorEmpty", onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          if (apiResponse.data['isSMSSent']) {
            _appState.setAppAuthToken = apiResponse.data['LogInTokenID'];
            print("============================");
            var zipcode = getZipCode();
            print("======== Zip Code =========== $zipcode ========");
            await sendActivationCode(otpTypeEnum: otpTypeEnum, phoneNumber: phoneNumberController.text, nationalIdOrFileNumber: nationalIdController.text, isForRegister: false, zipCode: zipcode);
          } else {
            if (apiResponse.data['IsAuthenticated']) {
              await checkActivationCode(
                otpTypeEnum: otpTypeEnum,
                onWrongActivationCode: (String? message) async {
                  await _dialogService.showCommonBottomSheetWithoutH(
                      message: message ?? "",
                      label: LocaleKeys.notice.tr(),
                      onOkPressed: () {
                        _navigationService.pop();
                      });
                },
                activationCode: null, //todo_section silent login case halded on the repo itself..
              );
            }
          }
        }
      },
    );
  }

  String getZipCode() {
    return selectedCountrySignup == CountryEnum.others
        ? "0"
        : (_appState.getSelectDeviceByImeiRespModelElement != null && _appState.getSelectDeviceByImeiRespModelElement!.outSa == true
            ? CountryEnum.unitedArabEmirates.countryCode.toString()
            : selectedCountrySignup.countryCode.toString());
  }

  Future<void> sendActivationCode(
      {required OTPTypeEnum otpTypeEnum,
      required String nationalIdOrFileNumber,
      required String phoneNumber,
      required bool isForRegister,
      dynamic payload,
      bool isComingFromResendOTP = false,
      bool isExcludedUser = false,
      bool isFormFamilyFile = false,
      bool isNeedLoading = false,
      int? responseID,
      String? zipCode}) async {
    var request = RequestUtils.getCommonRequestSendActivationCode(
        otpTypeEnum: otpTypeEnum,
        mobileNumber: phoneNumber,
        selectedLoginType: otpTypeEnum.toInt(),
        zipCode: zipCode ?? selectedCountrySignup.countryCode,
        nationalId: nationalIdOrFileNumber,
        isFileNo: isForRegister ? isPatientHasFile(request: payload) : false,
        patientId: isFormFamilyFile ? _appState.getAuthenticatedUser()!.patientId : 0,
        isForRegister: isForRegister,
        patientOutSA: isForRegister
            ? isPatientOutsideSA(request: payload)
            : selectedCountrySignup.countryCode == CountryEnum.saudiArabia.countryCode
                ? false
                : true,
        payload: payload,
        isExcludedUser: isExcludedUser,
        isFormFamilyFile: isFormFamilyFile,
        responseID: responseID);

    // TODO: GET APP SMS SIGNATURE HERE
    request.sMSSignature = await getSignature();

    // if(!kDebugMode) {
    //   // Get Turnstile token if configured
    //   final turnstileToken = await _turnstileService.getTurnstileToken();
    //   if (turnstileToken != null) {
    //     request.turnstileToken = turnstileToken;
    //   } else {
    //     request.turnstileToken = "";
    //   }
    // }

    if (isNeedLoading) {
      LoaderBottomSheet.showLoader();
    }
    if (checkIsUserComingForRegister(request: payload)) {
      _appState.setUserRegistrationPayload = RegistrationDataModelPayload.fromJson(payload);
    }

    final resultEither = await _authenticationRepo.sendActivationCodeRepo(
        sendActivationCodeReq: request, isRegister: checkIsUserComingForRegister(request: payload), languageID: 'er', isFormFamilyFile: isFormFamilyFile);

    resultEither.fold(
      (failure) async {
        LoaderBottomSheet.hideLoader();
        await _errorHandlerService.handleError(failure: failure);
      },
      (apiResponse) async {
        if (isFormFamilyFile) {
          if (apiResponse.data['PatientShareRequestID'] != null && apiResponse.data['PatientShareRequestID'] == 0 && apiResponse.messageStatus == 1) {
            LoaderBottomSheet.hideLoader();
            _dialogService.showErrorBottomSheet(
                message: apiResponse.data["ErrorMessage"],
                onOkPressed: () {
                  _navigationService.pop();
                });
            return;
          }
          patientShareRequestID = apiResponse.data['PatientShareRequestID'];
          _appState.setFamilyFileTokenID = apiResponse.data['LogInTokenID'];
        }
        if (apiResponse.messageStatus == 2) {
          LoaderBottomSheet.hideLoader();
          await _dialogService.showCommonBottomSheetWithoutH(
              message: apiResponse.errorMessage ?? "Something Went Wrong",
              onOkPressed: () {
                _navigationService.pop();
              });
        } else {
          if (apiResponse.data != null && apiResponse.data['isSMSSent'] == true) {
            LoaderBottomSheet.hideLoader();
            if (!isComingFromResendOTP) {
              navigateToOTPScreen(
                otpTypeEnum: otpTypeEnum,
                phoneNumber: phoneNumber,
                zipCode: zipCode ?? "",
                isComingFromRegister: checkIsUserComingForRegister(request: payload),
                payload: payload,
                isFormFamilyFile: isFormFamilyFile,
                isExcludedUser: isExcludedUser,
                responseID: responseID,
                patientShareRequestID: patientShareRequestID,
              );
            }
          } else {
            // TODO: Handle isSMSSent false
            // navigateToOTPScreen(otpTypeEnum: otpTypeEnum, phoneNumber: phoneNumber);
            if (isFormFamilyFile) {
              LoaderBottomSheet.hideLoader();
              await _dialogService.showCommonBottomSheetWithoutH(
                  message: LocaleKeys.unableToSendOTP.tr(),
                  label: LocaleKeys.notice.tr(),
                  onOkPressed: () {
                    _navigationService.pop();
                  });
            }
          }
        }
      },
    );
  }

  bool checkIsUserComingForRegister({required dynamic request}) {
    bool isUserComingForRegister = false;
    if (request != null && request['isRegister'] == true) {
      isUserComingForRegister = true;
    }
    return isUserComingForRegister;
  }

  Future<void> checkActivationCode({
    required String? activationCode,
    required OTPTypeEnum otpTypeEnum,
    required Function(String? message) onWrongActivationCode,
    Function()? onResendActivation,
    bool isFormFamilyFile = false,
    dynamic patientShareRequestID,
    dynamic responseID,
    bool isSwitchUser = false,
    int? patientID,
  }) async {
    bool isForRegister = (_appState.getUserRegistrationPayload.healthId != null || _appState.getUserRegistrationPayload.patientOutSa == true || _appState.getUserRegistrationPayload.patientOutSa == 1);
    MyAppointmentsViewModel myAppointmentsVM = getIt<MyAppointmentsViewModel>();

    if (isSwitchUser && _appState.getSuperUserID == null) {
      nationalIdController.text = responseID.toString();
    } else if (isSwitchUser && _appState.getSuperUserID != null) {
      nationalIdController.text = _appState.getSuperUserID.toString();
    }

    final request = RequestUtils.getCommonRequestWelcome(
            phoneNumber: phoneNumberController.text,
            otpTypeEnum: otpTypeEnum,
            deviceToken: _appState.deviceToken,
            // patientOutSA: _appState.getUserRegistrationPayload.projectOutSa == 1 ? true : false,
            patientOutSA: isForRegister
                ? _appState.getUserRegistrationPayload.projectOutSa == true
                    ? true
                    : false
                : _appState.getSelectDeviceByImeiRespModelElement != null
                    ? _appState.getSelectDeviceByImeiRespModelElement!.outSa!
                    : selectedCountrySignup == CountryEnum.saudiArabia
                        ? false
                        : true,
            loginTokenID: _appState.appAuthToken,
            registeredData: isForRegister ? _appState.getUserRegistrationPayload : null,
            nationIdText: nationalIdController.text,
            countryCode: _appState.getSelectDeviceByImeiRespModelElement != null && _appState.getSelectDeviceByImeiRespModelElement!.outSa == true
                ? CountryEnum.unitedArabEmirates.countryCode
                : selectedCountrySignup.countryCode,
            //TODO: Error Here IN Zip Code.
            loginType: loginTypeEnum.toInt)
        .toJson();

    LoaderBottomSheet.showLoader();
    if (isForRegister) {
      if (_appState.getUserRegistrationPayload.patientOutSa == 0) request['DOB'] = _appState.getUserRegistrationPayload.dob;
      request['HealthId'] = _appState.getUserRegistrationPayload.healthId;
      request['IsHijri'] = _appState.getUserRegistrationPayload.isHijri;
      request["PatientOutSA"] = _appState.getUserRegistrationPayload.projectOutSa == true ? 1 : 0;
      request["ForRegisteration"] = _appState.getUserRegistrationPayload.isRegister;
      request["isRegister"] = false;

      final resultEither = await _authenticationRepo.checkActivationCodeRepo(newRequest: request, activationCode: activationCode.toString(), isRegister: true);

      LoaderBottomSheet.hideLoader();

      resultEither.fold(
          (failure) async => await _errorHandlerService.handleError(
              failure: failure,
              onUnHandledFailure: (failure) async {
                LoaderBottomSheet.hideLoader();
                await _dialogService.showCommonBottomSheetWithoutH(
                    message: failure.message,
                    label: LocaleKeys.notice.tr(),
                    onOkPressed: () {
                      _navigationService.pop();
                    });
              }), (apiResponse) {
        final activation = CheckActivationCode.fromJson(apiResponse.data as Map<String, dynamic>);
        if (_appState.getUserRegistrationPayload.isRegister == true) {
          //TODO: KSA Version Came Hre
          loadCountriesData();
          _navigationService.pushAndReplace(AppRoutes.registerStepTwo);
          // Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: RegisterNew));
          return;
        }
      });
    } else {
      final resultEither = await _authenticationRepo.checkActivationCodeRepo(
          newRequest: CheckActivationCodeRegisterReq.fromJson(request),
          activationCode: activationCode,
          isRegister: false,
          isFormFamilyFile: isFormFamilyFile,
          patientShareRequestID: patientShareRequestID,
          responseID: responseID,
          isSwitchUser: isSwitchUser,
          patientID: patientID,
          // loginType: _appState.getSuperUserID != null ? 0 : 2,
          loginType: loginTypeEnum.toInt);

      resultEither.fold(
          (failure) async => await _errorHandlerService.handleError(
              failure: failure,
              onUnHandledFailure: (failure) async {
                LoaderBottomSheet.hideLoader();
                otpScreenNotifier.value = true;
                await _dialogService.showCommonBottomSheetWithoutH(message: failure.message, label: LocaleKeys.notice.tr(), onOkPressed: () {});
              },
              onMessageStatusFailure: (failure) async {
                LoaderBottomSheet.hideLoader();
                await _dialogService.showCommonBottomSheetWithoutH(message: failure.message, label: LocaleKeys.notice.tr(), onOkPressed: () {});
              }), (apiResponse) async {
        final activation = CheckActivationCode.fromJson(apiResponse.data as Map<String, dynamic>);

        if (activation.errorCode == '699') {
          // Todo: Hide Loader
          LoaderBottomSheet.hideLoader();
          onWrongActivationCode(activation.errorEndUserMessage);
          return;
        } else if (activation.messageStatus == 2) {
          LoaderBottomSheet.hideLoader();
          onWrongActivationCode(activation.errorEndUserMessage);
          return;
        } else if (_appState.getUserRegistrationPayload.isRegister == true) {
          LoaderBottomSheet.hideLoader();
          _navigationService.pushAndReplace(AppRoutes.registerStepTwo);
          // Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: RegisterNew));
          return;
        } else {
          if (isFormFamilyFile) {
            // await navigateToFamilyFilePage();
            MedicalFileViewModel medicalVm = getIt<MedicalFileViewModel>();
            if (!_appState.getIsChildLoggedIn) {
              await medicalVm.getFamilyFiles(status: 0);
              if (isFormFamilyFile) {
                await medicalVm.getAllPendingRecordsByResponseId();
                _navigationService.replaceAllRoutesAndNavigateToLandingWithMedicalAuth().whenComplete(() {
                  _navigationService.pushPageRoute(AppRoutes.familyFilesPage);
                });
              } else {
                _navigationService.replaceAllRoutesAndNavigateToLanding();
              }
              // await medicalVm.getAllPendingRecordsByResponseId();
            }
          } else {
            if (activation.list != null && activation.list!.isNotEmpty) {
              if (isSwitchUser) {
                // Clear profile image cache when switching users
                _appState.clearProfileImageCache();
                log("🔄 Switching user - cleared profile image cache");

                if (_appState.getIsChildLoggedIn) {
                  _appState.setSuperUserID = null;
                  // _appState.setIsChildLoggedIn = false;
                  activation.list!.first.isParentUser = false;
                  var allUsersPayload = _appState.getUserSwitchPayloads;
                  if ((allUsersPayload.containsKey('superUser') && allUsersPayload['superUser'] != null)) {
                    _appState.addUserSwitchPayload(activation.list!.first.toJson(), isSuperUser: false);
                  } else {
                    _appState.addUserSwitchPayload(activation.list!.first.toJson(), isSuperUser: true);
                  }
                } else {
                  var allUsersPayload = _appState.getUserSwitchPayloads;
                  _appState.setSuperUserID = allUsersPayload['superUser']?['PatientID'];
                  activation.list!.first.isParentUser = true;
                  _appState.addUserSwitchPayload(activation.list!.first.toJson(), isSuperUser: true);
                }

                // Fetch profile image after switching user
                // await _fetchProfileImage(activation.list!.first.patientId);
                _fetchProfileImage(activation.list!.first.patientId);
              } else {
                activation.list!.first.isParentUser = true;
                _appState.addUserSwitchPayload(activation.list!.first.toJson(), isSuperUser: true);

                // Fetch profile image after login
                // await _fetchProfileImage(activation.list!.first.patientId);
                _fetchProfileImage(activation.list!.first.patientId);
              }
              activation.list!.first.bloodGroup = activation.patientBloodType;
              activation.list!.first.zipCode = selectedCountrySignup == CountryEnum.others ? '0' : selectedCountrySignup.countryCode;
              _appState.setAuthenticatedUser(activation.list!.first);
              _appState.setPrivilegeModelList(activation.list!.first.listPrivilege!);
              _appState.setUserBloodGroup = activation.patientBlodType ?? "N/A";
              _appState.setIsPaytabsEnabled(Utils.havePrivilege(120));
              _appState.setIsPayfortHostedPageEnabled(Utils.havePrivilege(121));

              // Refresh privileges after user switching to ensure correct privileges are loaded
              if (isSwitchUser) {
                print("🔄 Switching user - refreshing privileges");
                await getServicePrivilege();
              }

              // Fetch patient blood type from new API
              // await getPatientBloodTypeNew();
            }
            // _appState.setUserBloodGroup = (activation.patientBlodType ?? "");
            _appState.setAppAuthToken = activation.authenticationTokenId;
            // myAppointmentsVM.getActiveAppointmentsCount();
            final request = RequestUtils.getAuthanticatedCommonRequest().toJson();
            bool isUserAgreedBefore = await checkIfUserAgreedBefore(request: request);

            //updating the last login type in app state to show the fingerprint/face id option on home screen
            if (_appState.getSelectDeviceByImeiRespModelElement != null) {
              _appState.getSelectDeviceByImeiRespModelElement!.logInType = loginTypeEnum.toInt;
            }

//
            if (!isSwitchUser && !_appState.getIsChildLoggedIn) {
              MedicalFileViewModel medicalVm = getIt<MedicalFileViewModel>();
              insertPatientIMEIData(loginTypeEnum.toInt);
              medicalVm.getFamilyFiles(status: 0); //TODO:  Remove status: 1 by Aamir Need to Discuss With Sultan
              // medicalVm.getAllPendingRecordsByResponseId();
            }
            await clearDefaultInputValues();
            myAppointmentsVM.setIsAppointmentDataToBeLoaded(true);
            getIt.get<HabibWalletViewModel>().setIsWalletAmountToBeLoaded(true);
            getIt.get<InsuranceViewModel>().setIsInsuranceDataToBeLoaded(true);
            getIt.get<HmgServicesViewModel>().setHasVitalSignDataLoaded(false);
            if (isUserAgreedBefore) {
              LoaderBottomSheet.hideLoader();
              navigateToHomeScreen();
            } else {
              LoaderBottomSheet.hideLoader();
              navigateToHomeScreen();
              //Agreement page not designed yet so we are navigating to home screen directly
              // getUserAgreementContent(request: request);
            }
            // TODO: setPreferences and stuff
            // sharedPref.remove(FAMILY_FILE);
            // activation.list!.isFamily = false;
            // userData = activation.list;
            // sharedPref.setString(BLOOD_TYPE, activation.patientBloodType ?? "");
            // authenticatedUserObject.user = activation.list!;
            // projectViewModel.setPrivilege(privilegeList: res);
            // await sharedPref.setObject(MAIN_USER, activation.list);
            // await sharedPref.setObject(USER_PROFILE, activation.list);
            // loginTokenID = activation.logInTokenID;
            // await sharedPref.setObject(LOGIN_TOKEN_ID, activation.logInTokenID);
            // await sharedPref.setString(TOKEN, activation.authenticationTokenID!);

            // projectViewModel.analytics.loginRegistration.login_successful();
          }
        }
      });
    }
  }

  Future<void> navigateToFamilyFilePage() async {
    MedicalFileViewModel medicalFileVM = GetIt.instance<MedicalFileViewModel>();
    medicalFileVM.handleFamilyFileRequestOTPVerification();
  }

  Future<bool> checkIfUserAgreedBefore({required dynamic request}) async {
    bool isAgreed = false;
    if (havePrivilege(109)) {
      final resultEither = await _authenticationRepo.checkIfUserAgreed(commonAuthanticatedRequest: request);
      resultEither.fold((failure) async => await _errorHandlerService.handleError(failure: failure), (apiResponse) {
        if (apiResponse.data['IsPatientAlreadyAgreed']) {
          return true;
        }
      });
    }
    return isAgreed;
  }

  Future<void> getUserAgreementContent({required dynamic request}) async {
    final resultEither = await _authenticationRepo.getUserAgreementContent(commonAuthanticatedRequest: request);
    resultEither.fold((failure) async => await _errorHandlerService.handleError(failure: failure), (apiResponse) async {
      // _navigationService.pushAndReplace(routeName)
      //TODO: Add User Agreement Page Here
    });
  }

  bool havePrivilege(int id) {
    bool isHavePrivilege = false;
    try {
      for (var element in _appState.getAuthenticatedUser()!.listPrivilege!) {
        if (element.id == id) isHavePrivilege = element.previlege!;
      }
    } catch (e) {
      print(e);
    }
    return isHavePrivilege;
  }

  Future<void> navigateToHomeScreen() async {
    setIsInitialLoginNavigated(true);
    getPatientBloodTypeNew();
    Navigator.pushAndRemoveUntil(
        _navigationService.navigatorKey.currentContext!,
        CustomPageRoute(
          page: LandingNavigation(),
        ),
        (r) => false);
  }

  Future<void> navigateToOTPScreen(
      {required OTPTypeEnum otpTypeEnum,
      required String phoneNumber,
      required bool isComingFromRegister,
      dynamic payload,
      bool isFormFamilyFile = false,
      bool isExcludedUser = false,
      int? responseID,
      int? patientShareRequestID,
      required String zipCode}) async {
    _navigationService.pushToOtpScreen(
      phoneNumber: phoneNumber,
      isFormFamilyFile: isFormFamilyFile,
      zipCode: zipCode,
      checkActivationCode: (int activationCode) async {
        await checkActivationCode(
          activationCode: activationCode.toString(),
          isFormFamilyFile: isFormFamilyFile,
          otpTypeEnum: otpTypeEnum,
          responseID: responseID,
          patientShareRequestID: patientShareRequestID,
          onWrongActivationCode: (String? value) {
            onWrongActivationCode(message: value);
          },
        );
      },
      onResendOTPPressed: (String phoneNumber, String zipCode) async {
        await sendActivationCode(
            otpTypeEnum: otpTypeEnum,
            phoneNumber: phoneNumberController.text,
            nationalIdOrFileNumber: nationalIdController.text,
            isForRegister: isComingFromRegister,
            isComingFromResendOTP: true,
            payload: payload,
            isFormFamilyFile: isFormFamilyFile,
            isExcludedUser: isExcludedUser,
            responseID: responseID,
            zipCode: zipCode);
      },
    );
  }

  Future<void> onWrongActivationCode({String? message}) async {
    otpScreenNotifier.value = true;
    await _dialogService.showErrorBottomSheet(
        message: message ?? "Something went wrong. ",
        onOkPressed: () {
          LoaderBottomSheet.hideLoader();
          _navigationService.pushAndReplace(AppRoutes.loginScreen);
        });
  }

  loginWithFingerPrintFace(Function success) async {
    _localAuthService.authenticate().then((value) async {
      if (value) {
        LoaderBottomSheet.showLoader();
        success();
        loginTypeEnum = (_appState.deviceTypeID == 1 ? LoginTypeEnum.face : LoginTypeEnum.fingerprint);
        if (!_appState.isAuthenticated) {
          //commenting this api to check either the same flow working or not because this api does not needed further if work fine we will remove this
          await getPatientDeviceData(loginTypeEnum.toInt);
        } else {
          // authenticated = true;
          await insertPatientIMEIData(loginTypeEnum.toInt);
          LoaderBottomSheet.hideLoader();
        }
        notifyListeners();
        // navigateToHomeScreen();
      } else {
        //authenticated = false;
        notifyListeners();
      }
    });
  }

  checkLastLoginStatus(Function() onSuccess) async {
    Future.delayed(Duration(seconds: 1), () async {
      if (cacheService.getBool(key: CacheConst.quickLoginEnabled) == null) {
        final deviceElement = _appState.getSelectDeviceByImeiRespModelElement;
        if (deviceElement != null && (deviceElement.logInType == 1 || deviceElement.logInType == 4)) {
          phoneNumberController.text = (_appState.getAuthenticatedUser()!.mobileNumber!.startsWith("0")
              ? _appState.getAuthenticatedUser()!.mobileNumber!.replaceFirst("0", "")
              : _appState.getAuthenticatedUser()!.mobileNumber)!;
          nationalIdController.text = _appState.getAuthenticatedUser()!.patientIdentificationNo!;
          onSuccess();
        } else if ((loginTypeEnum == LoginTypeEnum.sms || loginTypeEnum == LoginTypeEnum.whatsapp && deviceElement == null) && _appState.getAuthenticatedUser() != null) {
          phoneNumberController.text = (_appState.getAuthenticatedUser()!.mobileNumber!.startsWith("0")
              ? _appState.getAuthenticatedUser()!.mobileNumber!.replaceFirst("0", "")
              : _appState.getAuthenticatedUser()!.mobileNumber)!;
          nationalIdController.text = _appState.getAuthenticatedUser()!.patientIdentificationNo!;
          onSuccess();
        }
      }
    });
  }

  Future<void> onRegistrationStart({required OTPTypeEnum otpTypeEnum}) async {
    bool isOutSidePatient = selectedCountrySignup.countryCode == CountryEnum.unitedArabEmirates.countryCode ? true : false;
    LoaderBottomSheet.showLoader();
    final request = await RequestUtils.getPatientAuthenticationRequest(
            phoneNumber: phoneNumberController.text,
            nationId: nationalIdController.text,
            patientOutSA: isOutSidePatient,
            otpTypeEnum: otpTypeEnum,
            isForRegister: true,
            patientId: 0,
            zipCode: selectedCountrySignup.countryCode,
            calenderType: calenderType,
            dob: dob)
        .toJson();
    var nRequest = Map<String, dynamic>.from(request);

    if (true) {
      request.removeWhere((key, value) => value == null);
      nRequest.removeWhere((key, value) => value == null);
      nRequest.removeWhere((key, value) => key == "SearchType");
      nRequest.removeWhere((key, value) => key == "PatientID");
      nRequest.removeWhere((key, value) => key == "OTP_SendType");
      nRequest.removeWhere((key, value) => key == "LanguageID");
    }

    final resultEither = await _authenticationRepo.checkPatientForRegistration(commonAuthanticatedRequest: nRequest);
    resultEither.fold(
        (failure) async => await _errorHandlerService.handleError(
            failure: failure,
            onUnHandledFailure: (failur) {
              LoaderBottomSheet.hideLoader();
              _dialogService.showExceptionBottomSheet(
                  message: failur.message,
                  onOkPressed: () {
                    _navigationService.pop();
                  });
            }), (apiResponse) async {
      checkUserStatusForRegistration(response: apiResponse.data, request: request);
    });
  }

  Future<void> onRegistrationComplete() async {
    LoaderBottomSheet.showLoader();
    // LoadingUtils.showFullScreenLoader(loadingText: "Setting up your medical file.\nMay take a moment.");

    var request = RequestUtils.getUserSignupCompletionRequest(fullName: nameController.text, emailAddress: emailController.text, gender: genderType, maritalStatus: maritalStatus);

    final resultEither = await _authenticationRepo.registerUser(registrationPayloadDataModelRequest: request);
    resultEither.fold((failure) async => await _errorHandlerService.handleError(failure: failure), (apiResponse) async {
      if (apiResponse.data is String) {
        //TODO: This Section Need to Be Testing.
        LoaderBottomSheet.hideLoader();
        _dialogService.showExceptionBottomSheet(message: apiResponse.data, onOkPressed: () {}, onCancelPressed: () {});
        //TODO: Here We Need to Show a Dialog Of Something in the case of Fail With OK and Cancel and the Display Variable WIll be result.
      } else {
        LoaderBottomSheet.hideLoader();
        if (apiResponse.data["MessageStatus"] == 1) {
          LoaderBottomSheet.showLoader(loadingText: "Your medical file has been created successfully. \nPlease proceed to login.");
          //TODO: Here We Need to Show a Dialog Of Something in the case of Success.
          await clearDefaultInputValues(); // This will Clear All Default Values Of User.
          Future.delayed(Duration(seconds: 1), () {
            LoaderBottomSheet.hideLoader();
            // _navigationService.pushAndReplace(AppRoutes.loginScreen);
            _navigationService.pushAndRemoveUntil(CustomPageRoute(page: LandingNavigation()), (r) => false);
            _navigationService.push(CustomPageRoute(page: LoginScreen()));
          });
        } else {
          print("=========");
        }
      }
    });

    return;
  }

  Future<void> checkUserStatusForRegistration({required dynamic response, required dynamic request}) async {
    if (response is Map) {
      if (response["MessageStatus"] == 2) {
        LoaderBottomSheet.hideLoader();
        print(response["ErrorEndUserMessage"]);
        return;
      }
      if (response['hasFile'] == true) {
        //TODO: Show Here Ok And Cancel Dialog and On OKPress it will go for sendActivationCode
        LoaderBottomSheet.hideLoader();
        _dialogService.showCommonBottomSheetWithoutH(
            message: response["ErrorMessage"],
            onOkPressed: () async {
              await clearDefaultInputValues();
              _navigationService.pushAndReplace(AppRoutes.loginScreen);
            },
            onCancelPressed: () {
              _navigationService.pop();
            });
      } else {
        request['forRegister'] = true;
        request['isRegister'] = true;
        _appState.setAppAuthToken = response['LogInTokenID'];
        if (isPatientOutsideSA(request: response)) {
          sendActivationCode(
              otpTypeEnum: OTPTypeEnumExtension.fromInt(request["OTP_SendType"]),
              nationalIdOrFileNumber: request["PatientIdentificationID"].toString(),
              phoneNumber: request["PatientMobileNumber"].toString(),
              payload: request,
              isForRegister: true);
        } else {
          chekUserNHICData(request: request);
        }
      }
    } else {
      //TODO: Here Hide Loader And Show TOAST
      //TODO: if (response['ErrorCode'] == '-986') Toast With OK, And Show response as Output.
      LoaderBottomSheet.hideLoader();
      _dialogService.showErrorBottomSheet(message: response['ErrorMessage']);
    }
  }

  bool isPatientOutsideSA({required dynamic request}) {
    bool isOutSideSa = false;
    if (request["PatientOutSA"] == true || request["PatientOutSA"] == 1) {
      isOutSideSa = true;
    } else {
      isOutSideSa = false;
    }
    return isOutSideSa;
  }

  bool isPatientHasFile({required dynamic request}) {
    bool isFile = false;
    if (request != null && request["NationalID"] != null) {
      isFile = request["NationalID"].length < 10;
    }
    return isFile;
  }

  Future<void> chekUserNHICData({required dynamic request}) async {
    final resultEither = await _authenticationRepo.checkUserStatus(commonAuthanticatedRequest: request);
    resultEither.fold((failure) async => await _errorHandlerService.handleError(failure: failure), (apiResponse) async {
      if (apiResponse.data is Map) {
        setNHICData(apiResponse.data, request);
        sendActivationCode(
          otpTypeEnum: OTPTypeEnumExtension.fromInt(request["OTP_SendType"]),
          nationalIdOrFileNumber: request["PatientIdentificationID"].toString(),
          phoneNumber: request["PatientMobileNumber"].toString(),
          payload: request,
          isForRegister: true,
        );
      }
    });
  }

  void setNHICData(dynamic data, dynamic request) {
    _appState.setNHICUserData = CheckUserStatusResponseNHIC.fromJson(data as Map<String, dynamic>);
    request["healthId"] = _appState.getNHICUserData.healthId;
    _appState.setUserRegistrationPayload = RegistrationDataModelPayload.fromJson(request);
  }

  Future<void> insertPatientIMEIData(int loginType) async {
    final authenticatedUser = _appState.getAuthenticatedUser();
    if (authenticatedUser == null) {
      log("insertPatientIMEIData: authenticatedUser is null, skipping.");
      return;
    }
    if (authenticatedUser.patientId == null) {
      log("insertPatientIMEIData: patientId is null, skipping.");
      return;
    }
    final resultEither = await _authenticationRepo.insertPatientIMEIData(
        patientIMEIDataRequest: PatientInsertDeviceImei(
                imei: _appState.deviceToken,
                deviceTypeId: _appState.getDeviceTypeID(),
                patientId: authenticatedUser.patientId!,
                patientIdentificationNo: authenticatedUser.patientIdentificationNo ?? '',
                identificationNo: authenticatedUser.patientIdentificationNo ?? '',
                firstName: authenticatedUser.firstName ?? '',
                lastName: authenticatedUser.lastName ?? '',
                patientTypeId: authenticatedUser.patientType,
                mobileNo: authenticatedUser.mobileNumber ?? '',
                logInTypeId: loginType,
                patientOutSa: authenticatedUser.outSa ?? 0,
                outSa: authenticatedUser.outSa == 1 ? true : false,
                biometricEnabled: loginType == 1 || loginType == 2 ? false : true,
                firstNameN: authenticatedUser.firstNameN,
                lastNameN: authenticatedUser.lastNameN,
                zipCode: authenticatedUser.zipCode //selectedCountrySignup == CountryEnum.others ? '0': selectedCountrySignup.countryCode,
                )
            .toJson());
    resultEither.fold((failure) async => await _errorHandlerService.handleError(failure: failure), (apiResponse) async {
      if (apiResponse.messageStatus == 1) {
        log("Insert IMEI Success");
        insertPatientDeviceData(loginType);
      } else {
        log("Insert IMEI Failed");
      }
    });
  }

  Future<void> insertPatientDeviceData(int loginType) async {
    final authenticatedUser = _appState.getAuthenticatedUser();
    if (authenticatedUser == null || authenticatedUser.patientId == null) {
      log("insertPatientDeviceData: authenticatedUser or patientId is null, skipping.");
      return;
    }
    final resultEither = await _authenticationRepo.insertPatientDeviceData(
        patientDeviceDataRequest: InsertPatientMobileDeviceInfo(
                deviceToken: _appState.deviceToken,
                deviceTypeId: _appState.getDeviceTypeID(),
                patientId: authenticatedUser.patientId!,
                patientTypeId: authenticatedUser.patientType,
                patientOutSa: authenticatedUser.outSa ?? 0,
                loginType: loginType,
                languageId: _appState.getLanguageID(),
                latitude: _appState.userLat,
                longitude: _appState.userLong,
                voipToken: "",
                deviceType: _appState.deviceTypeID,
                patientMobileNumber: authenticatedUser.mobileNumber,
                nationalId: authenticatedUser.patientIdentificationNo,
                gender: authenticatedUser.gender)
            .toJson());
    resultEither.fold((failure) async {
      // await _errorHandlerService.handleError(failure: failure);
    }, (apiResponse) async {
      if (apiResponse.messageStatus == 2) {}
      if (apiResponse.messageStatus == 1) {
        log("Insert Device Data Success");
      } else {
        log("Insert IMEI Failed");
      }
    });
  }

  Future<void> getPatientDeviceData(int loginType) async {
    final resultEither = await _authenticationRepo.getPatientDeviceData(
        patientDeviceDataRequest: GetUserMobileDeviceData(
                deviceToken: _appState.deviceToken,
                deviceTypeId: _appState.getDeviceTypeID(),
                patientId: _appState.getSelectDeviceByImeiRespModelElement!.patientId!,
                patientType: _appState.getSelectDeviceByImeiRespModelElement!.patientType,
                patientOutSa: _appState.getSelectDeviceByImeiRespModelElement!.outSa == true ? 1 : 0,
                projectOutSa: _appState.getSelectDeviceByImeiRespModelElement!.outSa,
                loginType: loginType,
                languageId: _appState.getLanguageID(),
                latitude: _appState.userLat,
                longitude: _appState.userLong,
                mobileNo: _appState.getSelectDeviceByImeiRespModelElement!.mobile!,
                patientMobileNumber: int.parse(_appState.getSelectDeviceByImeiRespModelElement!.mobile!),
                nationalId: _appState.getSelectDeviceByImeiRespModelElement!.identificationNo,
                zipCode: _appState.getSelectDeviceByImeiRespModelElement!.isOther == true
                    ? "0"
                    : _appState.getSelectDeviceByImeiRespModelElement!.outSa == true
                        ? CountryEnum.unitedArabEmirates.countryCode
                        : CountryEnum.saudiArabia.countryCode,
                isRegister: false,
                logInTokenId: "",
                searchType: 2,
                patientIdentificationId: "0",
                otpSendType: loginType)
            .toJson());

    resultEither.fold((failure) async => await _errorHandlerService.handleError(failure: failure), (apiResponse) async {
      if (apiResponse.messageStatus == 1) {
        dynamic deviceInfo = apiResponse.data['List_MobileLoginInfo'];
        getDeviceLastLogin = deviceInfo.first['LoginType'];
        await checkActivationCode(otpTypeEnum: OTPTypeEnum.faceIDFingerprint, activationCode: null, onWrongActivationCode: (String? message) {});
        await insertPatientIMEIData(loginTypeEnum.toInt);
        LoaderBottomSheet.hideLoader();
      }
      if (apiResponse.messageStatus == 2) {
        LoaderBottomSheet.hideLoader();
        await _dialogService.showCommonBottomSheetWithoutH(
            message: apiResponse.errorMessage ?? "",
            label: LocaleKeys.notice.tr(),
            onOkPressed: () {
              _dialogService.showPhoneNumberPickerSheet(
                  // label: "Where would you like to receive OTP?",
                  label: LocaleKeys.receiveOtpToast.tr(),
                  message: _appState.isArabic() ? "يرجى الاختيار من الخيارات أدناه لاستلام رمز التحقق." : "Please select from the below options to receive OTP.",
                  onSMSPress: () {
                    checkUserAuthentication(otpTypeEnum: OTPTypeEnum.sms);
                  },
                  onWhatsappPress: () {
                    checkUserAuthentication(otpTypeEnum: OTPTypeEnum.whatsapp);
                  });
            },
            onCancelPressed: () {
              _navigationService.pop();
            });
      }
    });
  }

  @override
  void dispose() {
    nationalIdController.dispose();
    phoneNumberController.dispose();
    myFocusNode.dispose();
    super.dispose();
  }

  Future<void> getServicePrivilege() async {
    ApiConsts.setBackendURLs();
    final resultEither = await _authenticationRepo.getServicePrivilege();
    List<ListPrivilege> privilegeModelList = [];
    List<VidaPlusProjectListModel> vidaPlusProjectListModel = [];
    List<HMCProjectListModel> hMCProjectListModel = [];
    List<ProjectDetailListModel> projectDetailListModel = [];

    resultEither.fold(
      // (failure) async => await _errorHandlerService.handleError(failure: failure),
      (failure) async {
        print(failure.message);
      },
      (apiResponse) async {
        if (apiResponse.messageStatus == 2) {
          await _dialogService.showErrorBottomSheet(message: apiResponse.errorMessage ?? "ErrorEmpty");
        } else {
          apiResponse.data["ServicePrivilegeList"].forEach((v) {
            privilegeModelList.add(ListPrivilege.fromJson(v));
          });
          _appState.setPrivilegeModelList(privilegeModelList.cast<ListPrivilege>());

          apiResponse.data["ProjectListVidaPlus"].forEach((v) {
            vidaPlusProjectListModel.add(VidaPlusProjectListModel.fromJson(v));
          });
          _appState.setVidaPlusProjectList(vidaPlusProjectListModel);

          apiResponse.data["HMCProjectList"].forEach((v) {
            hMCProjectListModel.add(HMCProjectListModel.fromJson(v));
          });
          _appState.setHMCProjectList(hMCProjectListModel);

          apiResponse.data["ProjectDetailList"].forEach((v) {
            projectDetailListModel.add(ProjectDetailListModel.fromJson(v));
          });
          _appState.setProjectsDetailList(projectDetailListModel);
          _appState.setIsPaytabsEnabled(Utils.havePrivilege(120));
          _appState.setIsPayfortHostedPageEnabled(Utils.havePrivilege(121));
        }
      },
    );
  }

  Future<String?> getSignature() async {
    if (Platform.isAndroid) {
      return await SmsVerification.getAppSignature();
    } else {
      return null;
    }
  }

  Future<void> logout() async {
    try {
      // Clear user data from AppState
      _appState.setAuthenticatedUser(null);
      _appState.setAuthenticatedUser(null, isFamily: true);
      _appState.setIsAuthenticated = false;
      _appState.setAppAuthToken = "";
      _appState.setUserBloodGroup = "";
      _appState.clearProfileImageCache(); // Clear profile image cache
      _appState.setSuperUserID = null;
      _appState.setIsChildLoggedIn = false;
      _appState.setFamilyFileTokenID = "";
      _appState.setSelectDeviceByImeiRespModelElement(null);
      _appState.setNHICUserData = CheckUserStatusResponseNHIC();
      _appState.setUserRegistrationPayload = RegistrationDataModelPayload();
      // Clear privilege lists
      _appState.setPrivilegeModelList([]);
      _appState.setVidaPlusProjectList([]);
      _appState.setHMCProjectList([]);
      _appState.setProjectsDetailList([]);
      _appState.clearUserSwitchPayloads();
      await clearDefaultInputValues();
      _navigationService.pushAndReplace(AppRoutes.landingScreen);
    } catch (e) {
      _navigationService.pushAndReplace(AppRoutes.landingScreen);
    }
  }

  Future<void> getPatientBloodTypeNew() async {
    try {
      final result = await _authenticationRepo.getPatientBloodType();

      result.fold(
        (failure) async {
          // Log error but don't show to user, keep existing blood type
          log("Failed to fetch blood type: ${failure.message}");
        },
        (apiResponse) {
          if (apiResponse.messageStatus == 1 && apiResponse.data != null) {
            // Extract blood type from response
            String? bloodType = apiResponse.data['GetPatientBloodType'][0]["BloodType"];
            if (bloodType != null && bloodType.isNotEmpty) {
              _appState.setUserBloodGroup = bloodType;
              log("Blood type updated from new API: $bloodType");
            }
          }
        },
      );
    } catch (e) {
      log("Error calling getPatientBloodType: $e");
    }
  }

  /// Fetch profile image after login and store in AppState
  Future<void> _fetchProfileImage(int? patientID) async {
    if (patientID == null) return;

    try {
      log("Fetching profile image for patient ID: $patientID");

      // IMPORTANT: Clear old cache BEFORE fetching new image
      // This ensures old data is removed immediately
      _appState.clearProfileImageCache();
      log("🧹 Cleared profile image cache before fetch");

      final profileSettingsRepo = GetIt.instance<ProfileSettingsRepo>();
      final result = await profileSettingsRepo.getProfileImage(patientID: patientID);

      result.fold(
        (failure) {
          // Silently fail - profile image is optional
          log("Failed to fetch profile image: ${failure.message}");
          // Ensure cache is cleared even on failure
          _appState.setProfileImageData = null;
        },
        (apiResponse) {
          if (apiResponse.data != null && apiResponse.data['Patient_GetProfileImageDataList'] != null) {
            var imageList = apiResponse.data['Patient_GetProfileImageDataList'];
            if (imageList is List && imageList.isNotEmpty) {
              String? imageData = imageList[0]['ImageData'];
              if (imageData != null && imageData.isNotEmpty) {
                // Set new profile image data - this will update cache and notify all listeners
                _appState.setProfileImageData = imageData;
                log("✅ Profile image loaded and cached successfully for patient: $patientID");
              } else {
                log("⚠️ Profile image data is empty for patient: $patientID");
                _appState.setProfileImageData = null;
              }
            } else {
              log("⚠️ Profile image list is empty for patient: $patientID");
              _appState.setProfileImageData = null;
            }
          } else {
            log("⚠️ No profile image data in response for patient: $patientID");
            _appState.setProfileImageData = null;
          }
        },
      );
    } catch (e) {
      log("❌ Error fetching profile image: $e");
      _appState.setProfileImageData = null;
    }
  }
}
