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

import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/common_models/generic_api_model.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/features/book_appointments/book_appointments_repo.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_repo.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/cmc_create_new_order_req_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/create_e_referral_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/order_update_req_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/search_e_referral_req_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/send_activation_code_ereferral_req_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/covid_get_test_proceedure_resp.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_all_cities_resp_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_all_orders_resp_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_services_resp_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/search_e_referral_resp_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/vital_sign_respo_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:sms_otp_auto_verify/sms_otp_auto_verify.dart';

import 'models/req_models/check_activation_e_referral_req_model.dart';
import 'models/resq_models/get_covid_payment_info_resp.dart';
import 'models/resq_models/relationship_type_resp_mode.dart';
import 'models/ui_models/covid_questionnare_model.dart';

class HmgServicesViewModel extends ChangeNotifier {
  final HmgServicesRepo hmgServicesRepo;
  final BookAppointmentsRepo bookAppointmentsRepo;
  final ErrorHandlerService errorHandlerService;
  final NavigationService navigationService;

  HmgServicesViewModel({required this.bookAppointmentsRepo, required this.hmgServicesRepo, required this.errorHandlerService, required this.navigationService});

  bool isCmcOrdersLoading = false;
  bool isCmcServicesLoading = false;
  bool isUpdatingOrder = false;
  bool isHospitalListLoading = false;
  bool isVitalSignLoading = false;

  bool hasVitalSignDataLoaded = false;

  // HHC specific loading states
  bool isHhcOrdersLoading = false;
  bool isHhcServicesLoading = false;

  List<GetCMCAllOrdersResponseModel> cmcOrdersList = [];
  List<GetCMCServicesResponseModel> cmcServicesList = [];
  List<HospitalsModel> hospitalsList = [];
  List<HospitalsModel> filteredHospitalsList = [];
  HospitalsModel? selectedHospital;
  List<VitalSignResModel> vitalSignList = [];

  // Vital Sign PageView Controller
  PageController _vitalSignPageController = PageController();

  PageController get vitalSignPageController => _vitalSignPageController;

  int _vitalSignCurrentPage = 0;

  int get vitalSignCurrentPage => _vitalSignCurrentPage;

  void setVitalSignCurrentPage(int page) {
    _vitalSignCurrentPage = page;
    notifyListeners();
  }

  // HHC specific lists
  List<GetCMCAllOrdersResponseModel> hhcOrdersList = [];
  List<GetCMCServicesResponseModel> hhcServicesList = [];

  // CMC order creation state
  HospitalsModel? selectedHospitalForOrder;
  GetCMCServicesResponseModel? selectedServiceForOrder;

  // HHC order creation state (no hospital selection needed for home healthcare)
  GetCMCServicesResponseModel? selectedServiceForHhcOrder;

  List<GetAllRelationshipTypeResponseModel> relationTypes = [];
  List<GetAllCitiesResponseModel> getAllCitiesList = [];
  List<SearchEReferralResponseModel> searchReferralList = [];
  List<Covid19GetTestProceduresResp> covidTestProcedureList = [];
  Covid19GetPaymentInfo? covidPaymentInfo;

  void setHasVitalSignDataLoaded(bool hasVitalSignDataLoaded) {
    this.hasVitalSignDataLoaded = hasVitalSignDataLoaded;
    notifyListeners();
  }

  Future<void> getOrdersList() async {}

  // HHC multiple services selection
  List<GetCMCServicesResponseModel> selectedHhcServices = [];

  Future<void> getCmcOrdersList() async {
    cmcOrdersList.clear();
    isCmcOrdersLoading = true;
    notifyListeners();
    await getAllCmcOrders();
  }

  // Helper to sort hospitals by distance (ascending). Safely converts distanceinkMS to double.
  void _sortHospitalsByDistance(List<HospitalsModel> list) {
    double toDouble(dynamic v) {
      if (v == null) return double.infinity;
      if (v is num) return v.toDouble();
      if (v is String) return double.tryParse(v) ?? double.infinity;
      return double.infinity;
    }

    list.sort((a, b) {
      final da = toDouble(a.distanceInKilometers);
      final db = toDouble(b.distanceInKilometers);
      return da.compareTo(db);
    });
  }

  Future<void> getAllCmcOrders({
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    isCmcOrdersLoading = true;
    notifyListeners();

    final result = await hmgServicesRepo.getAllComprehensiveCheckupOrders();

    result.fold(
      (failure) async {
        isCmcOrdersLoading = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isCmcOrdersLoading = false;
        if (apiResponse.messageStatus == 1) {
          cmcOrdersList = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> getAllCmcServices({required int patientID, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isCmcServicesLoading = true;
    notifyListeners();

    final result = await hmgServicesRepo.getAllCmcServices(patientID: patientID);

    result.fold(
      (failure) async {
        isCmcServicesLoading = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isCmcServicesLoading = false;
        if (apiResponse.messageStatus == 1) {
          cmcServicesList = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<bool> updateCmcPresOrder({
    required OrderUpdateRequestModel requestModel,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    isUpdatingOrder = true;
    notifyListeners();

    final result = await hmgServicesRepo.updateCmcPresOrder(requestModel);

    bool success = false;

    result.fold(
      (failure) async {
        isUpdatingOrder = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isUpdatingOrder = false;
        if (apiResponse.messageStatus == 1) {
          success = true;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );

    return success;
  }

  Future<void> getHospitalsList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isHospitalListLoading = true;
    notifyListeners();

    final result = await hmgServicesRepo.getHospitalsList();

    result.fold(
      (failure) async {
        isHospitalListLoading = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isHospitalListLoading = false;
        if (apiResponse.messageStatus == 1) {
          hospitalsList = apiResponse.data ?? [];
          filteredHospitalsList = List.from(hospitalsList);
          // ensure hospitals are sorted by distance before showing
          _sortHospitalsByDistance(filteredHospitalsList);
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  void filterHospitalsByString(String searchText, bool isArabic) {
    if (searchText.isEmpty) {
      filteredHospitalsList = List.from(hospitalsList);
      _sortHospitalsByDistance(filteredHospitalsList);
    } else {
      filteredHospitalsList = hospitalsList.where((HospitalsModel hospital) {
        final name = isArabic ? (hospital.nameN ?? '') : (hospital.name ?? '');
        return name.toLowerCase().contains(searchText.toLowerCase());
      }).toList();
      _sortHospitalsByDistance(filteredHospitalsList);
    }
    notifyListeners();
  }

  void setSelectedHospital(HospitalsModel? hospital) {
    selectedHospital = hospital;
    notifyListeners();
  }

  void clearHospitalSelection() {
    selectedHospital = null;
    filteredHospitalsList = List.from(hospitalsList);
    _sortHospitalsByDistance(filteredHospitalsList);
    notifyListeners();
  }

  // CMC Order management methods
  void setSelectedHospitalForOrder(HospitalsModel? hospital) {
    selectedHospitalForOrder = hospital;
    notifyListeners();
  }

  void setSelectedServiceForOrder(GetCMCServicesResponseModel? service) {
    selectedServiceForOrder = service;
    notifyListeners();
  }

  void clearOrderSelection() {
    selectedHospitalForOrder = null;
    selectedServiceForOrder = null;
    notifyListeners();
  }

  bool get isOrderReadyToConfirm => selectedHospitalForOrder != null && selectedServiceForOrder != null;

  Future<int?> addCmcOrder({
    required int projectID,
    required int orderServiceID,
    required List<PatientERCMCInsertServicesList> services,
    Function(int)? onSuccess,
    Function(String)? onError,
  }) async {
    isUpdatingOrder = true;
    notifyListeners();

    final result = await hmgServicesRepo.addCmcOrder(
      projectID: projectID,
      orderServiceID: orderServiceID,
      services: services,
    );

    int requestId = 0;

    result.fold(
      (failure) async {
        isUpdatingOrder = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isUpdatingOrder = false;
        if (apiResponse.messageStatus == 1) {
          requestId = apiResponse.data ?? 0;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(requestId);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );

    return requestId;
  }

//    ******************* HOME HEALTHCARE APIs ********************

  Future<void> getHhcOrdersList() async {
    hhcOrdersList.clear();
    isHhcOrdersLoading = true;
    notifyListeners();
    await getAllHhcOrders();
  }

  Future<void> getAllHhcOrders({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isHhcOrdersLoading = true;
    notifyListeners();

    final result = await hmgServicesRepo.getAllHomeHealthCareCheckupOrders();

    result.fold(
      (failure) async {
        isHhcOrdersLoading = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isHhcOrdersLoading = false;
        if (apiResponse.messageStatus == 1) {
          hhcOrdersList = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> getAllHhcServices({required int patientID, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isHhcServicesLoading = true;
    notifyListeners();

    final result = await hmgServicesRepo.getAllHhcServices(patientID: patientID);

    result.fold(
      (failure) async {
        isHhcServicesLoading = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isHhcServicesLoading = false;
        if (apiResponse.messageStatus == 1) {
          hhcServicesList = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<bool> updateHhcPresOrder({
    required OrderUpdateRequestModel requestModel,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    isUpdatingOrder = true;
    notifyListeners();

    final result = await hmgServicesRepo.updateHhcPresOrder(requestModel);

    bool success = false;

    result.fold(
      (failure) async {
        isUpdatingOrder = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isUpdatingOrder = false;
        if (apiResponse.messageStatus == 1) {
          success = true;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );

    return success;
  }

  Future<int?> addHhcOrder({
    required int projectID,
    required int orderServiceID,
    required List<PatientERCMCInsertServicesList> services,
    Function(int)? onSuccess,
    Function(String)? onError,
  }) async {
    isUpdatingOrder = true;
    notifyListeners();

    final result = await hmgServicesRepo.addHhcOrder(
      projectID: projectID,
      orderServiceID: orderServiceID,
      services: services,
    );

    int requestId = 0;

    result.fold(
      (failure) async {
        isUpdatingOrder = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isUpdatingOrder = false;
        if (apiResponse.messageStatus == 1) {
          requestId = apiResponse.data ?? 0;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(requestId);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );

    return requestId;
  }

  // HHC Order management methods (no hospital selection for home healthcare)
  void setSelectedServiceForHhcOrder(GetCMCServicesResponseModel? service) {
    selectedServiceForHhcOrder = service;
    notifyListeners();
  }

  void clearHhcOrderSelection() {
    selectedServiceForHhcOrder = null;
    selectedHhcServices.clear();
    notifyListeners();
  }

  bool get isHhcOrderReadyToConfirm => selectedServiceForHhcOrder != null;

  // Multiple HHC services selection methods
  void toggleHhcServiceSelection(GetCMCServicesResponseModel service) {
    final index = selectedHhcServices.indexWhere((s) => s.iD == service.iD);
    if (index != -1) {
      selectedHhcServices.removeAt(index);
    } else {
      selectedHhcServices.add(service);
    }
    notifyListeners();
  }

  bool isHhcServiceSelected(GetCMCServicesResponseModel service) {
    return selectedHhcServices.any((s) => s.iD == service.iD);
  }

  double getHhcSelectedServicesTotal() {
    double total = 0.0;
    for (var service in selectedHhcServices) {
      total += (service.priceTotal ?? 0);
    }
    return total;
  }

  void clearHhcServicesSelection() {
    selectedHhcServices.clear();
    notifyListeners();
  }

  /*e-referral functions*/

  Future<void> getRelationshipType({
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    notifyListeners();
    final result = await hmgServicesRepo.getRelationshipTypes();

    result.fold(
      (failure) async {
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          relationTypes = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> getAllCities({
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    notifyListeners();
    final result = await hmgServicesRepo.getAllCities();

    result.fold(
      (failure) async {
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          getAllCitiesList = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> eReferralSendActivationCode({
    required SendActivationCodeForEReferralRequestModel requestModel,
    Function(GenericApiModel)? onSuccess,
    Function(String)? onError,
  }) async {
    // Get and set the SMS signature for auto-fill
    requestModel.sMSSignature = await getSignature();

    notifyListeners();

    final result = await hmgServicesRepo.sendEReferralActivationCode(requestModel);

    result.fold(
      (failure) async {
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

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

  Future<void> checkEReferralActivationCode({
    required CheckActivationCodeForEReferralRequestModel requestModel,
    Function(GenericApiModel)? onSuccess,
    Function(String)? onError,
  }) async {
    notifyListeners();

    final result = await hmgServicesRepo.checkEReferralActivationCode(requestModel);

    result.fold(
      (failure) async {
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> createEReferral({
    required CreateEReferralRequestModel requestModel,
    Function(GenericApiModel)? onSuccess,
    Function(String)? onError,
  }) async {
    notifyListeners();

    final result = await hmgServicesRepo.createEReferral(requestModel);

    result.fold(
      (failure) async {
        notifyListeners();
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> searchEReferral({
    required SearchEReferralRequestModel requestModel,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    notifyListeners();

    final result = await hmgServicesRepo.searchEReferral(requestModel);

    result.fold(
      (failure) async {
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          searchReferralList = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> navigateToOTPScreen({
    required OTPTypeEnum otpTypeEnum,
    required String phoneNumber,
    required String loginToken,
    required Function onSuccess,
  }) async {
    navigationService.pushToOtpScreen(
      phoneNumber: phoneNumber,
      isFormFamilyFile: false,
      zipCode: "",
      checkActivationCode: (int activationCode) async {
        checkEReferralActivationCode(
          requestModel: CheckActivationCodeForEReferralRequestModel(
            logInTokenID: loginToken,
            activationCode: activationCode.toString(),
          ),
          onSuccess: (GenericApiModel response) {
            onSuccess();
          },
          onError: (String errorMessage) {
            print(errorMessage);
          },
        );
      },
      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,
        // );
      },
    );
  }

  List<CovidQuestionnaireModel> getQuestionsFromJson() {
    final String questionsJson =
        '''[   { "id": 1, "questionEN": "Is the test intended for travel?", "questionAR": "هل تجري التحليل بغرض السفر؟", "ans": 2 },   { "id": 2, "questionEN": "Coming from outside KSA within last 2 weeks?", "questionAR": "هل قدمت من خارج المملكة خلال الأسبوعين الماضيين؟", "ans": 2 },   { "id": 3, "questionEN": "Do you currently have fever?", "questionAR": "هل تعاني حاليا من حرارة؟", "ans": 2 },   { "id": 4, "questionEN": "Did you have fever in last 2 weeks?", "questionAR": "هل عانيت من حرارة في الأسبوعين الماضيين؟", "ans": 2 },   { "id": 5, "questionEN": "Do you have a sore throat?", "questionAR": "هل لديك التهاب في الحلق؟", "ans": 2 },   { "id": 6, "questionEN": "Do you have a runny nose?", "questionAR": "هل لديك سيلان بالأنف؟" },   { "id": 7, "questionEN": "Do you have a cough?", "questionAR": "هل لديك سعال؟", "ans": 2 },   { "id": 8, "questionEN": "Do you have shortness of breath?", "questionAR": "هل تعاني من ضيق في التنفس؟", "ans": 2 },   { "id": 9, "questionEN": "Do you have nausea?", "questionAR": "هل تعاني من غثيان؟", "ans": 2 },   { "id": 10, "questionEN": "Do you have vomiting?", "questionAR": "هل تعاني من القيء؟", "ans": 2 },   { "id": 11, "questionEN": "Do you have a headache?", "questionAR": "هل تعاني من صداع في الرأس؟", "ans": 2 },   { "id": 12, "questionEN": "Do you have muscle pain?", "questionAR": "هل تعانين من آلام عضلية؟", "ans": 2 },   { "id": 13, "questionEN": "Do you have joint pain?", "questionAR": "هل تعاني من آلام المفاصل؟", "ans": 2 },   { "id": 14, "questionEN": "Do you have diarrhea?", "questionAR": "هل لديك اسهال؟", "ans": 2 } ]''';

    try {
      final parsed = json.decode(questionsJson) as List<dynamic>;
      return parsed.map((e) => CovidQuestionnaireModel.fromJson(Map<String, dynamic>.from(e))).toList();
    } catch (_) {
      return <CovidQuestionnaireModel>[];
    }
  }

  Future<void> getCovidProcedureList({
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    notifyListeners();

    final result = await hmgServicesRepo.getCovidTestProcedures();

    result.fold(
      (failure) async {
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          covidTestProcedureList = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> getPaymentInfo({
    String? procedureID,
    int? projectID,
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    notifyListeners();

    final result = await hmgServicesRepo.getCovidPaymentInfo(procedureID!, projectID!);

    result.fold(
      (failure) async {
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          covidPaymentInfo = apiResponse.data;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  Future<void> getPatientVitalSign({
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    if (hasVitalSignDataLoaded) return;
    isVitalSignLoading = true;
    notifyListeners();

    final result = await hmgServicesRepo.getPatientVitalSign();

    result.fold(
      (failure) async {
        isVitalSignLoading = false;
        notifyListeners();
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.message);
        }
      },
      (apiResponse) {
        isVitalSignLoading = false;
        if (apiResponse.messageStatus == 1) {
          vitalSignList = apiResponse.data ?? [];
          hasVitalSignDataLoaded = true;
          if (vitalSignList.isNotEmpty) {
            getIt.get<SymptomsCheckerViewModel>().setSelectedHeight(vitalSignList.first.heightCm);
            getIt.get<SymptomsCheckerViewModel>().setSelectedWeight(vitalSignList.first.weightKg);
          }
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        } else {
          notifyListeners();
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        }
      },
    );
  }

  @override
  void dispose() {
    _vitalSignPageController.dispose();
    super.dispose();
  }
}
