import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_state.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/exceptions/api_failure.dart';
import 'package:hmg_patient_app_new/core/utils/request_utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/features/authentication/authentication_view_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/book_appointments/models/resp_models/get_allergies_response_model.dart';
import 'package:hmg_patient_app_new/features/common/models/family_file_request.dart';
import 'package:hmg_patient_app_new/features/medical_file/medical_file_repo.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/family_file_response_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/patient_medical_response_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/patient_sickleave_response_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/patient_vaccine_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.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/navigation_service.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';

class MedicalFileViewModel extends ChangeNotifier {
  int selectedTabIndex = 0;
  bool isPatientVaccineListLoading = false;
  bool isPatientSickLeaveListLoading = false;
  bool isPatientSickLeavePDFLoading = false;
  bool isPatientMedicalReportsListLoading = false;
  bool isPatientAllergiesListLoading = false;
  bool _isFamilyFilesLoading = false;

  bool get isFamilyFilesLoading => _isFamilyFilesLoading;

  set setIsFamilyFilesLoading(bool value) => _isFamilyFilesLoading = value;
  MedicalFileRepo medicalFileRepo;
  ErrorHandlerService errorHandlerService;

  List<PatientVaccineResponseModel> patientVaccineList = [];
  List<PatientSickLeavesResponseModel> patientSickLeaveList = [];

  List<SickLeaveList> patientSickLeavesByClinic = [];
  List<SickLeaveList> patientSickLeavesByHospital = [];
  List<SickLeaveList> patientSickLeavesViewList = [];

  bool isSickLeavesSortByClinic = true;

  bool isSickLeavesDataNeedsReloading = true;

  List<GetAllergiesResponseModel> patientAllergiesList = [];

  List<PatientMedicalReportResponseModel> patientMedicalReportList = [];

  List<PatientMedicalReportResponseModel> patientMedicalReportRequestedList = [];
  List<PatientMedicalReportResponseModel> patientMedicalReportReadyList = [];
  List<PatientMedicalReportResponseModel> patientMedicalReportCancelledList = [];

  List<MedicalReportList> patientMedicalReportsByClinic = [];
  List<MedicalReportList> patientMedicalReportsByHospital = [];
  List<MedicalReportList> patientMedicalReportsViewList = [];

  bool isMedicalReportsSortByClinic = true;

  List<PatientAppointmentHistoryResponseModel> patientMedicalReportAppointmentHistoryList = [];
  PatientAppointmentHistoryResponseModel? patientMedicalReportSelectedAppointment;

  List<FamilyFileResponseModelLists> patientFamilyFiles = [];
  List<FamilyFileResponseModelLists> pendingFamilyFiles = [];

  String patientSickLeavePDFBase64 = "";
  String patientMedicalReportPDFBase64 = "";

  int selectedMedicalReportsTabIndex = 0;
  int _selectedFamilyFileTabIndex = 0;

  int get getSelectedFamilyFileTabIndex => _selectedFamilyFileTabIndex;

  set setSelectedFamilyFileTabIndex(int value) {
    if (_selectedFamilyFileTabIndex != value) {
      _selectedFamilyFileTabIndex = value;
      notifyListeners();
    }
  }

  static final DialogService _dialogService = getIt.get<DialogService>();
  final AppState _appState = getIt<AppState>();
  AuthenticationViewModel authVM = getIt.get<AuthenticationViewModel>();

  MedicalFileViewModel({required this.medicalFileRepo, required this.errorHandlerService});

  initMedicalFileProvider() {
    patientMedicalReportAppointmentHistoryList.clear();
    patientAllergiesList.clear();
    isPatientVaccineListLoading = true;
    isPatientMedicalReportsListLoading = true;
    isPatientAllergiesListLoading = true;
    notifyListeners();
  }

  void onMedicalReportTabChange(int index) {
    selectedMedicalReportsTabIndex = index;
    print("Selected Medical Report Tab Index: $selectedMedicalReportsTabIndex");
    if (index == 0) {
      patientMedicalReportList = patientMedicalReportRequestedList;
    } else if (index == 1) {
      patientMedicalReportList = patientMedicalReportReadyList;
    } else if (index == 2) {
      patientMedicalReportList = patientMedicalReportCancelledList;
    }
    // Re-group by clinic/hospital for the selected tab
    _groupMedicalReportsByClinicAndHospital();
    notifyListeners();
  }

  void _groupMedicalReportsByClinicAndHospital() {
    patientMedicalReportsByClinic.clear();
    patientMedicalReportsByHospital.clear();

    for (var element in patientMedicalReportList) {
      // Group by clinic
      List<MedicalReportList> reportsByClinic = patientMedicalReportsByClinic.where((elementClinic) => elementClinic.filterName == element.clinicDescription).toList();

      if (reportsByClinic.isNotEmpty) {
        patientMedicalReportsByClinic[patientMedicalReportsByClinic.indexOf(reportsByClinic[0])].medicalReportsList!.add(element);
      } else {
        patientMedicalReportsByClinic.add(MedicalReportList(filterName: element.clinicDescription, medicalReport: element));
      }

      // Group by hospital
      List<MedicalReportList> reportsByHospital = patientMedicalReportsByHospital.where((elementHospital) => elementHospital.filterName == element.projectName).toList();

      if (reportsByHospital.isNotEmpty) {
        patientMedicalReportsByHospital[patientMedicalReportsByHospital.indexOf(reportsByHospital[0])].medicalReportsList!.add(element);
      } else {
        patientMedicalReportsByHospital.add(MedicalReportList(filterName: element.projectName, medicalReport: element));
      }
    }

    if (isMedicalReportsSortByClinic) {
      patientMedicalReportsViewList = patientMedicalReportsByClinic;
    } else {
      patientMedicalReportsViewList = patientMedicalReportsByHospital;
    }
  }

  setIsMedicalReportsSortByClinic(bool value) {
    isMedicalReportsSortByClinic = value;
    if (isMedicalReportsSortByClinic) {
      patientMedicalReportsViewList = patientMedicalReportsByClinic;
    } else {
      patientMedicalReportsViewList = patientMedicalReportsByHospital;
    }
    notifyListeners();
  }

  void onFamilyFileTabChange(int index) {
    setSelectedFamilyFileTabIndex = index;
  }

  setIsPatientVaccineListLoading(bool isLoading) {
    isPatientVaccineListLoading = isLoading;
    notifyListeners();
  }

  setIsPatientSickLeavePDFLoading(bool isLoading) {
    isPatientSickLeavePDFLoading = isLoading;
    notifyListeners();
  }

  setIsPatientSickLeaveListLoading(bool val) {
    if (val && isSickLeavesDataNeedsReloading) {
      patientSickLeaveList.clear();
      patientSickLeavesByClinic.clear();
    patientSickLeavesByHospital.clear();
    patientSickLeavesViewList.clear();
    patientSickLeavePDFBase64 = "";
    isSickLeavesSortByClinic = true;
    isPatientSickLeaveListLoading = val;
    }
    notifyListeners();
  }

  setIsSickLeavesSortByClinic(bool value) {
    isSickLeavesSortByClinic = value;
    if (isSickLeavesSortByClinic) {
      patientSickLeavesViewList = patientSickLeavesByClinic;
    } else {
      patientSickLeavesViewList = patientSickLeavesByHospital;
    }
    notifyListeners();
  }

  setIsPatientMedicalReportsLoading(bool val) {
    if (val) {
      onMedicalReportTabChange(0);
      patientMedicalReportList.clear();
      patientMedicalReportsByClinic.clear();
      patientMedicalReportsByHospital.clear();
      patientMedicalReportsViewList.clear();
      patientMedicalReportPDFBase64 = "";
      isMedicalReportsSortByClinic = true;
    }
    isPatientMedicalReportsListLoading = val;
    notifyListeners();
  }

  setSelectedMedicalReportAppointment(PatientAppointmentHistoryResponseModel? val) {
    patientMedicalReportSelectedAppointment = val;
    notifyListeners();
  }

  void onTabChanged(int index) {
    selectedTabIndex = index;
    notifyListeners();
  }

  Future<void> getPatientVaccinesList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    patientVaccineList.clear();
    final result = await medicalFileRepo.getPatientVaccinesList();

    result.fold(
      (failure) async {
        print("❌ Vaccine API Failure: ${failure.message}");
        isPatientVaccineListLoading = false;
        notifyListeners();
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        print("📦 Vaccine API Response - Status: ${apiResponse.messageStatus}, Data: ${apiResponse.data}");

        if (apiResponse.messageStatus == 2) {
          print("⚠️ Vaccine API Error: ${apiResponse.errorMessage}");
          isPatientVaccineListLoading = false;
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? "Unknown error");
          }
        } else if (apiResponse.messageStatus == 1) {
          if (apiResponse.data != null) {
            patientVaccineList = apiResponse.data!;
            print("✅ Vaccine data loaded: ${patientVaccineList.length} items");
          } else {
            print("⚠️ Vaccine API returned success but data is null");
          }
          isPatientVaccineListLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          print("⚠️ Unexpected messageStatus: ${apiResponse.messageStatus}");
          isPatientVaccineListLoading = false;
          notifyListeners();
        }
      },
    );
  }

  Future<void> getPatientAllergiesList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isPatientAllergiesListLoading = true;
    patientAllergiesList.clear();
    notifyListeners();
    final result = await medicalFileRepo.getPatientAllergiesList();

    result.fold(
      (failure) async {
        isPatientAllergiesListLoading = false;
        notifyListeners();
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientAllergiesList = apiResponse.data!;
          isPatientAllergiesListLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getPatientSickLeaveList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    if (!isSickLeavesDataNeedsReloading) {
      return;
    }

    patientSickLeaveList.clear();
    notifyListeners();

    final result = await medicalFileRepo.getPatientSickLeavesList();

    result.fold(
      // (failure) async => await errorHandlerService.handleError(
      //   failure: failure,
      //   onOkPressed: () {
      //     onError!(failure.message);
      //   },
      // ),
      (failure) async {
        isPatientSickLeaveListLoading = false;
        isSickLeavesDataNeedsReloading = true;
        notifyListeners();
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientSickLeaveList = apiResponse.data!;
          isPatientSickLeaveListLoading = false;

          // Group by clinic and hospital
          for (var element in patientSickLeaveList) {
            // Group by clinic
            List<SickLeaveList> sickLeavesByClinic = patientSickLeavesByClinic.where((elementClinic) => elementClinic.filterName == element.clinicName).toList();

            if (sickLeavesByClinic.isNotEmpty) {
              patientSickLeavesByClinic[patientSickLeavesByClinic.indexOf(sickLeavesByClinic[0])].sickLeavesList!.add(element);
            } else {
              patientSickLeavesByClinic.add(SickLeaveList(filterName: element.clinicName, sickLeaves: element));
            }

            // Group by hospital
            List<SickLeaveList> sickLeavesByHospital = patientSickLeavesByHospital.where((elementHospital) => elementHospital.filterName == element.projectName).toList();

            if (sickLeavesByHospital.isNotEmpty) {
              patientSickLeavesByHospital[patientSickLeavesByHospital.indexOf(sickLeavesByHospital[0])].sickLeavesList!.add(element);
            } else {
              patientSickLeavesByHospital.add(SickLeaveList(filterName: element.projectName, sickLeaves: element));
            }
          }
          patientSickLeavesViewList = patientSickLeavesByClinic;
          isSickLeavesDataNeedsReloading = false;

          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getPatientSickLeavePDF(PatientSickLeavesResponseModel patientSickLeavesResponseModel, AuthenticatedUser authenticatedUser,
      {Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await medicalFileRepo.getPatientSickLeavePDF(patientSickLeavesResponseModel, authenticatedUser);

    result.fold(
      (failure) async => await errorHandlerService.handleError(
        failure: failure,
        onOkPressed: () {
          onError!(failure.message);
        },
      ),
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientSickLeavePDFBase64 = apiResponse.data!;
          isPatientSickLeaveListLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getPatientMedicalReportList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    patientMedicalReportList.clear();
    patientMedicalReportRequestedList.clear();
    patientMedicalReportReadyList.clear();
    patientMedicalReportCancelledList.clear();
    notifyListeners();

    final result = await medicalFileRepo.getPatientMedicalReportsList();

    result.fold(
      (failure) async => await errorHandlerService.handleError(
        failure: failure,
        onOkPressed: () {
          onError!(failure.message);
        },
      ),
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientMedicalReportList = apiResponse.data!;
          if (patientMedicalReportList.isNotEmpty) {
            patientMedicalReportRequestedList = patientMedicalReportList.where((element) => element.status == 1).toList();
            patientMedicalReportReadyList = patientMedicalReportList.where((element) => element.status == 2).toList();
            patientMedicalReportCancelledList = patientMedicalReportList.where((element) => element.status == 4).toList();
          }
          onMedicalReportTabChange(0);
          isPatientMedicalReportsListLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getPatientMedicalReportPDF(PatientMedicalReportResponseModel patientMedicalReportResponseModel, AuthenticatedUser authenticatedUser,
      {Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await medicalFileRepo.getPatientMedicalReportPDF(patientMedicalReportResponseModel, authenticatedUser);

    result.fold(
      (failure) async => await errorHandlerService.handleError(
        failure: failure,
        onOkPressed: () {
          onError!(failure.message);
        },
      ),
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientMedicalReportPDFBase64 = apiResponse.data!;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getFamilyFiles({int? status, Function(dynamic)? onSuccess, Function(String)? onError}) async {

    setIsFamilyFilesLoading = true;
    
    final shouldShowLoader = patientFamilyFiles.isEmpty;
    if (shouldShowLoader) {
      LoaderBottomSheet.showLoader();
    }

    final result = await medicalFileRepo.getPatientFamilyFiles(status, _appState.getSuperUserID != null ? _appState.getSuperUserID! : _appState.getAuthenticatedUser()!.patientId!);

    result.fold(
      (failure) async {

        setIsFamilyFilesLoading = false;
        
        await errorHandlerService.handleError(
          failure: failure,
          onOkPressed: () {
            if (shouldShowLoader) {
              LoaderBottomSheet.hideLoader();
            }
            onError!(failure.message);
          },
        );
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {

          setIsFamilyFilesLoading = false;
          
          // _dialogService.showErrorBottomSheet(message: apiResponse.errorMessage!, onOkPressed: () {});
          if (shouldShowLoader) {
            LoaderBottomSheet.hideLoader();
          }
        } else if (apiResponse.messageStatus == 1) {
          if (apiResponse.data != null) {
            final currentUser = _appState.getAuthenticatedUser()!;
            final currentUserFamilyFile = FamilyFileResponseModelLists(
              patientId: currentUser.patientId,
              patientName: '${currentUser.firstName!} ${currentUser.lastName!}',
              isActive: true,
              gender: currentUser.gender!,
              responseId: currentUser.patientId,
              age: currentUser.age,
              mobileNumber: currentUser.mobileNumber,
              patientIdenficationNumber: currentUser.patientIdentificationNo,
              emaiLAddress: currentUser.emailAddress,
              genderDescription: currentUser.genderDescription,
              patientImageData: _appState.getProfileImageData, // Set main user's profile image
            );

            // Clear and start fresh with current user
            final List<FamilyFileResponseModelLists> newPatientFamilyFiles = [currentUserFamilyFile];

            final List<FamilyFileResponseModelLists> activeFamilyFiles = [];
            final List<FamilyFileResponseModelLists> newPendingFamilyFiles = [];

            for (var element in apiResponse.data!) {
              if (element.status == null) {
                continue;
              }

              final isPending = element.status == FamilyFileEnum.pending.toInt || element.status == FamilyFileEnum.rejected.toInt;
              final isActive = element.status == FamilyFileEnum.active.toInt;

              if (!isPending && !isActive) {
                continue;
              }

              final familyFile = FamilyFileResponseModelLists(
                id: element.id,
                patientId: element.patientId,
                patientName: element.patientName!,
                isActive: element.isActive,
                gender: element.gender!,
                responseId: element.responseId,
                mobileNumber: element.mobileNumber,
                age: element.age,
                patientIdenficationNumber: element.patientIdenficationNumber,
                relationship: element.relationship,
                relationshipId: element.relationshipId,
                relationshipN: element.relationshipN,
                status: element.status,
                statusDescription: element.statusDescription,
                createdOn: element.createdOn,
                editedOn: element.editedOn,
                patientDataVerified: element.patientDataVerified,
                regionId: element.regionId,
                familyRegionId: element.familyRegionId,
                genderDescription: element.genderDescription,
                genderImage: element.genderImage,
                emaiLAddress: element.emaiLAddress,
                patientImageData: element.patientImageData, // Include profile image data
              );

              if (isPending) {
                familyFile.isRequestFromMySide = true;
                newPendingFamilyFiles.add(familyFile);
              }
              if (isActive) {
                activeFamilyFiles.add(familyFile);
              }
            }

            for (var activeFile in activeFamilyFiles) {
              if (!newPatientFamilyFiles.any((e) => e.responseId == activeFile.responseId)) {
                newPatientFamilyFiles.add(activeFile);
              }
            }

            // Assign new list instances
            patientFamilyFiles = newPatientFamilyFiles;
            pendingFamilyFiles = newPendingFamilyFiles;
          }

          // Clear loading state on success
          setIsFamilyFilesLoading = false;

          if (shouldShowLoader) {
            LoaderBottomSheet.hideLoader();
          }
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getAllPendingRecordsByResponseId() async {
    AppState appState = getIt<AppState>();
    final result = await medicalFileRepo.getAllPendingRecordsByResponseId(request: {'ResponseID': appState.getAuthenticatedUser()!.patientId ?? "0", "Status": 2});

    result.fold(
      // (failure) async => await errorHandlerService.handleError(failure: failure),
      (failure) async {
        log("Error in fetching pending family files: ${failure.message}");
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // _dialogService.showErrorBottomSheet(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          if (apiResponse.data != null) {
            final List<FamilyFileResponseModelLists> tempPendingFamilyFiles = [];
            for (var element in apiResponse.data!) {
              if (element.status != null && element.status == FamilyFileEnum.pending.toInt || element.status == FamilyFileEnum.active.toInt) {
                tempPendingFamilyFiles.add(FamilyFileResponseModelLists(
                    id: element.id,
                    patientId: element.patientId,
                    patientName: element.patientName!,
                    isActive: element.status,
                    gender: element.gender,
                    responseId: element.patientId,
                    mobileNumber: element.mobileNumber,
                    age: element.age,
                    patientIdenficationNumber: element.patientIdenficationNumber,
                    relationship: element.relationship,
                    relationshipId: element.relationshipId,
                    relationshipN: element.relationshipN,
                    status: element.status,
                    statusDescription: element.statusDescription,
                    createdOn: element.createdOn,
                    editedOn: element.editedOn,
                    patientDataVerified: element.patientDataVerified,
                    regionId: element.regionId,
                    familyRegionId: element.familyRegionId,
                    genderDescription: element.genderDescription,
                    genderImage: element.genderImage,
                    emaiLAddress: element.emaiLAddress));
              }
            }
            // pendingFamilyFiles.addAll(tempPendingFamilyFiles.where((element) => !pendingFamilyFiles.any((e) => e.responseId == element.responseId)));
            final existingIds = pendingFamilyFiles.map((e) => e.patientId).toSet();
            final newItems = tempPendingFamilyFiles.where((element) => !existingIds.contains(element.patientId)).toList();
            pendingFamilyFiles = [...pendingFamilyFiles, ...newItems];
          }
          notifyListeners();
        }
      },
    );
  }

  Future<void> switchFamilyFiles({Function(dynamic)? onSuccess, int? responseID, int? patientID, String? phoneNumber, Function(String)? onError}) async {
    authVM.phoneNumberController.text = phoneNumber!.startsWith("0") ? phoneNumber.replaceFirst("0", "") : phoneNumber;

    await authVM.checkActivationCode(
      activationCode: '0000',
      otpTypeEnum: OTPTypeEnum.sms,
      onWrongActivationCode: (String? str) {},
      responseID: responseID,
      isFormFamilyFile: false,
      isSwitchUser: true,
      patientID: patientID,
    );
  }

  Future<void> addFamilyFile({required OTPTypeEnum otpTypeEnum}) async {
    LoaderBottomSheet.showLoader();
    AuthenticationViewModel authVM = getIt.get<AuthenticationViewModel>();
    NavigationService navigationService = getIt.get<NavigationService>();
    FamilyFileRequest request =
        await RequestUtils.getAddFamilyRequest(nationalIDorFile: authVM.nationalIdController.text, mobileNo: authVM.phoneNumberController.text, countryCode: authVM.selectedCountrySignup.countryCode);

    final resultEither = await medicalFileRepo.addFamilyFile(request: request.toJson());
    resultEither.fold(
        (failure) async => await errorHandlerService.handleError(
            failure: failure,
            onUnHandledFailure: (failure) {
              LoaderBottomSheet.hideLoader();
              _dialogService.showErrorBottomSheet(
                  message: failure.message,
                  onOkPressed: () {
                    navigationService.pop();
                  });
            }), (apiResponse) async {
      if (apiResponse.messageStatus == 2) {
        LoaderBottomSheet.hideLoader();
        _dialogService.showErrorBottomSheet(
            message: apiResponse.errorMessage!,
            onOkPressed: () {
              navigationService.pop();
            });
      } else if (apiResponse.messageStatus == 1) {
        if (apiResponse.data != null) {
          request.isPatientExcluded = apiResponse.data["IsPatientExcluded"];
          request.responseID = apiResponse.data["ReponseID"];
          LoaderBottomSheet.hideLoader();
          _dialogService.showExceptionBottomSheet(
              message: apiResponse.data["Message"],
              onOkPressed: () {
                navigationService.pop();
                authVM.sendActivationCode(
                    otpTypeEnum: otpTypeEnum,
                    nationalIdOrFileNumber: request.sharedPatientIdentificationId!,
                    phoneNumber: request.sharedPatientMobileNumber!,
                    isForRegister: false,
                    isExcludedUser: apiResponse.data['IsPatientExcluded'],
                    responseID: apiResponse.data["ReponseID"],
                    isNeedLoading: true,
                    isFormFamilyFile: true);
              },
              onCancelPressed: () {
                navigationService.pop();
              });
        }
      }
    });
  }

  Future<void> clearAuthValues() async {
    authVM.nationalIdController.clear();
    authVM.phoneNumberController.clear();
    authVM.emailController.clear();
    authVM.dobController.clear();
  }

  Future<void> handleFamilyFileRequestOTPVerification() async {
    if (!_appState.getIsChildLoggedIn) {
      await getFamilyFiles(status: 0);
      await getAllPendingRecordsByResponseId();
    }
  }

  Future<void> removeFileFromFamilyMembers({int? id}) async {
    NavigationService navigationService = getIt.get<NavigationService>();
    _dialogService.showExceptionBottomSheet(
        message: "Remove this member?",
        onOkPressed: () async {
          LoaderBottomSheet.showLoader();
          final result = await medicalFileRepo.removeFamilyFile(id: id);
          result.fold(
            (failure) async => await errorHandlerService.handleError(failure: failure),
            (apiResponse) {
              if (apiResponse.messageStatus == 2) {
                LoaderBottomSheet.hideLoader();
                _dialogService.showErrorBottomSheet(
                    message: apiResponse.errorMessage!,
                    onOkPressed: () {
                      navigationService.pop();
                    });
              } else if (apiResponse.messageStatus == 1) {
                patientFamilyFiles = patientFamilyFiles.where((element) => element.id != id).toList();
                getFamilyFiles();
                getAllPendingRecordsByResponseId();
                LoaderBottomSheet.hideLoader();
                notifyListeners();
                navigationService.pop();
              }
            },
          );
        },
        onCancelPressed: () {
          navigationService.pop();
        });
  }

  Future<void> getPatientMedicalReportAppointmentsList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    patientMedicalReportAppointmentHistoryList.clear();
    notifyListeners();

    final result = await medicalFileRepo.getPatientAppointmentsForMedicalReport();

    result.fold(
      (failure) async {
        onError!(failure.message);
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientMedicalReportAppointmentHistoryList = apiResponse.data!;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> insertRequestForMedicalReport({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await medicalFileRepo.insertRequestForMedicalReport(appointmentHistoryResponseModel: patientMedicalReportSelectedAppointment!);

    result.fold(
      (failure) async {
        onError!(failure.message);
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> acceptRejectFileFromFamilyMembers({int? id, int? status}) async {
    NavigationService navigationService = getIt.get<NavigationService>();
    LoaderBottomSheet.showLoader();
    final result = await medicalFileRepo.acceptRejectFamilyFile(id: id, status: status);
    result.fold(
      (failure) async => await errorHandlerService.handleError(failure: failure),
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          LoaderBottomSheet.hideLoader();
          // _dialogService.showErrorBottomSheet(
          //     message: apiResponse.errorMessage!,
          //     onOkPressed: () {
          //       navigationService.pop();
          //     });
        } else if (apiResponse.messageStatus == 1) {
          // FamilyFileResponseModelLists moveProfile = pendingFamilyFiles.firstWhere((element) => element.id == patientID);
          // moveProfile.status = 3;
          // moveProfile.statusDescription = "Approved";
          // patientFamilyFiles.add(moveProfile);
          pendingFamilyFiles = pendingFamilyFiles.where((element) => element.id != id).toList();
          //TODO: Call Api Here To Load Family Members
          getFamilyFiles(status: 0);
          getAllPendingRecordsByResponseId();
          LoaderBottomSheet.hideLoader();
          notifyListeners();
          // onFamilyFileTabChange(0);
        }
      },
    );
  }

  /// Update family member's profile image in cached family files
  void updateFamilyMemberProfileImage(int patientID, String imageData) {
    try {
      bool updated = false;

      // Update in patientFamilyFiles list
      for (var i = 0; i < patientFamilyFiles.length; i++) {
        if (patientFamilyFiles[i].patientId == patientID ||
            patientFamilyFiles[i].responseId == patientID) {
          patientFamilyFiles[i].patientImageData = imageData;
          updated = true;
          print("✅ Updated profile image for family member in patientFamilyFiles (index: $i, patientID: $patientID)");
          break;
        }
      }

      // Update in pendingFamilyFiles list if exists
      for (var i = 0; i < pendingFamilyFiles.length; i++) {
        if (pendingFamilyFiles[i].patientId == patientID ||
            pendingFamilyFiles[i].responseId == patientID) {
          pendingFamilyFiles[i].patientImageData = imageData;
          print("✅ Updated profile image for pending family member (index: $i, patientID: $patientID)");
          break;
        }
      }

      if (updated) {
        // Create new list instances to trigger Selector rebuild
        patientFamilyFiles = List.from(patientFamilyFiles);
        pendingFamilyFiles = List.from(pendingFamilyFiles);

        // Notify listeners to update UI
        notifyListeners();
        print("🔄 Created new list instances and notified listeners");
      } else {
        print("⚠️ Family member not found in cache for patientID: $patientID");
      }
    } catch (e) {
      print("❌ Error updating family member profile image in cache: $e");
    }
  }
}
