import 'dart:developer';

import 'package:dartz/dartz.dart';
import 'package:hmg_patient_app_new/core/api/api_client.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart';
import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/check_activation_e_referral_req_model.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/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/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/my_appointments/models/resp_models/hospital_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

import 'models/req_models/create_e_referral_model.dart';
import 'models/req_models/send_activation_code_ereferral_req_model.dart';
import 'models/resq_models/covid_get_test_proceedure_resp.dart';
import 'models/resq_models/get_covid_payment_info_resp.dart';
import 'models/resq_models/relationship_type_resp_mode.dart';
import 'models/resq_models/search_e_referral_resp_model.dart';
import 'models/resq_models/vital_sign_respo_model.dart';

abstract class HmgServicesRepo {
  Future<Either<Failure, GenericApiModel<List<GetCMCAllOrdersResponseModel>>>> getAllComprehensiveCheckupOrders();

  Future<Either<Failure, GenericApiModel<List<GetCMCAllOrdersResponseModel>>>> getAllHomeHealthCareCheckupOrders();

  Future<Either<Failure, GenericApiModel<bool>>> updateCmcPresOrder(OrderUpdateRequestModel requestModel);

  Future<Either<Failure, GenericApiModel<bool>>> updateHhcPresOrder(OrderUpdateRequestModel requestModel);

  Future<Either<Failure, GenericApiModel<List<GetCMCServicesResponseModel>>>> getAllCmcServices({required int patientID});

  Future<Either<Failure, GenericApiModel<List<GetCMCServicesResponseModel>>>> getAllHhcServices({required int patientID});

  Future<Either<Failure, GenericApiModel<List<HospitalsModel>>>> getHospitalsList();

  Future<Either<Failure, GenericApiModel<int>>> addCmcOrder({
    required int projectID,
    required int orderServiceID,
    required List<PatientERCMCInsertServicesList> services,
  });

  Future<Either<Failure, GenericApiModel<int>>> addHhcOrder({
    required int projectID,
    required int orderServiceID,
    required List<PatientERCMCInsertServicesList> services,
  });

  Future<Either<Failure, GenericApiModel<List<GetAllRelationshipTypeResponseModel>>>> getRelationshipTypes();

  Future<Either<Failure, GenericApiModel<List<GetAllCitiesResponseModel>>>> getAllCities();

  Future<Either<Failure, GenericApiModel<String>>> sendEReferralActivationCode(SendActivationCodeForEReferralRequestModel requestModel);

  Future<Either<Failure, GenericApiModel<String>>> checkEReferralActivationCode(CheckActivationCodeForEReferralRequestModel requestModel);

  Future<Either<Failure, GenericApiModel<String>>> createEReferral(CreateEReferralRequestModel requestModel);


  Future<Either<Failure, GenericApiModel<List<SearchEReferralResponseModel>>>> searchEReferral(SearchEReferralRequestModel requestModel);

  Future<Either<Failure, GenericApiModel<List<Covid19GetTestProceduresResp>>>> getCovidTestProcedures();

  Future<Either<Failure, GenericApiModel<Covid19GetPaymentInfo>>> getCovidPaymentInfo(String procedureID, int projectID);

  Future<Either<Failure, GenericApiModel<List<VitalSignResModel>>>> getPatientVitalSign();
}

class HmgServicesRepoImp implements HmgServicesRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

  HmgServicesRepoImp({required this.apiClient, required this.loggerService});

  @override
  Future<Either<Failure, GenericApiModel<List<GetCMCAllOrdersResponseModel>>>> getAllComprehensiveCheckupOrders() async {
    Map<String, dynamic> requestBody = {};

    try {
      GenericApiModel<List<GetCMCAllOrdersResponseModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.allCMCOrdersRc,
        isRCService: true,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("CMC Orders API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<GetCMCAllOrdersResponseModel> cmcOrdersList = [];
            // Log the full response for debugging
            // Extract MessageStatus and ErrorEndUserMessage from root level
            final apiErrorMessage = response['ErrorEndUserMessage'] as String?;
            // Parse the response array
            if (response['response'] != null && response['response'] is List) {
              final ordersList = response['response'] as List;

              for (var orderJson in ordersList) {
                if (orderJson is Map<String, dynamic>) {
                  try {
                    cmcOrdersList.add(GetCMCAllOrdersResponseModel.fromJson(orderJson));
                  } catch (e) {
                    loggerService.logError("Error parsing individual order: ${e.toString()}");
                  }
                }
              }
            }

            apiResponse = GenericApiModel<List<GetCMCAllOrdersResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: apiErrorMessage ?? errorMessage,
              data: cmcOrdersList,
            );
          } catch (e) {
            loggerService.logError("Error parsing CMC orders: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      loggerService.logError("Unknown error in getAllCmcOrders: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<GetCMCAllOrdersResponseModel>>>> getAllHomeHealthCareCheckupOrders() async {
    Map<String, dynamic> requestBody = {};

    try {
      GenericApiModel<List<GetCMCAllOrdersResponseModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.allHHCOrdersRc,
        isRCService: true,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("HHC Orders API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<GetCMCAllOrdersResponseModel> cmcOrdersList = [];
            // Log the full response for debugging
            // Extract MessageStatus and ErrorEndUserMessage from root level
            final apiErrorMessage = response['ErrorEndUserMessage'] as String?;
            // Parse the response array
            if (response['response'] != null && response['response'] is List) {
              final ordersList = response['response'] as List;

              for (var orderJson in ordersList) {
                if (orderJson is Map<String, dynamic>) {
                  try {
                    cmcOrdersList.add(GetCMCAllOrdersResponseModel.fromJson(orderJson));
                  } catch (e) {
                    loggerService.logError("Error parsing individual order: ${e.toString()}");
                  }
                }
              }
            }

            apiResponse = GenericApiModel<List<GetCMCAllOrdersResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: apiErrorMessage ?? errorMessage,
              data: cmcOrdersList,
            );
          } catch (e) {
            loggerService.logError("Error parsing HHC orders: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      loggerService.logError("Unknown error in getAllHHCOrders: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<GetCMCServicesResponseModel>>>> getAllCmcServices({required int patientID}) async {
    Map<String, dynamic> requestBody = {};

    try {
      GenericApiModel<List<GetCMCServicesResponseModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        '${ApiConsts.allCMCServicesRc}?patientID=$patientID',
        isRCService: true,
        isAllowAny: true,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("CMC Services API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<GetCMCServicesResponseModel> cmcServicesList = [];

            if (response['response'] != null && response['response'] is List) {
              final servicesList = response['response'] as List;

              for (var serviceJson in servicesList) {
                if (serviceJson is Map<String, dynamic>) {
                  cmcServicesList.add(GetCMCServicesResponseModel.fromJson(serviceJson));
                }
              }
            }

            apiResponse = GenericApiModel<List<GetCMCServicesResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: cmcServicesList,
            );
          } catch (e) {
            loggerService.logError("Error parsing CMC services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in getAllCmcServices: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<GetCMCServicesResponseModel>>>> getAllHhcServices({required int patientID}) async {
    Map<String, dynamic> requestBody = {};

    try {
      GenericApiModel<List<GetCMCServicesResponseModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        '${ApiConsts.allHHCServicesRc}?patientID=$patientID',
        isRCService: true,
        isAllowAny: true,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("HHC Services API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<GetCMCServicesResponseModel> hhcServicesList = [];

            if (response['response'] != null && response['response'] is List) {
              final servicesList = response['response'] as List;

              for (var serviceJson in servicesList) {
                if (serviceJson is Map<String, dynamic>) {
                  hhcServicesList.add(GetCMCServicesResponseModel.fromJson(serviceJson));
                }
              }
            }

            apiResponse = GenericApiModel<List<GetCMCServicesResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: hhcServicesList,
            );
          } catch (e) {
            loggerService.logError("Error parsing HHC services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in getAllHhcServices: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<bool>>> updateCmcPresOrder(OrderUpdateRequestModel requestModel) async {
    try {
      GenericApiModel<bool>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.updateCMCOrder,
        isRCService: true,
        body: requestModel.toJson(),
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("Update CMC Order API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<bool>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: true,
            );

            loggerService.logInfo("CMC Order updated successfully: PresOrderID=${requestModel.presOrderID}");
          } catch (e) {
            loggerService.logError("Error processing update CMC order response: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      loggerService.logError("Unknown error in updateCmcPresOrder: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<bool>>> updateHhcPresOrder(OrderUpdateRequestModel requestModel) async {
    try {
      GenericApiModel<bool>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.updateHHCOrder,
        isRCService: true,
        body: requestModel.toJson(),
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("Update HHC Order API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<bool>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: true,
            );

            loggerService.logInfo("HHC Order updated successfully: PresOrderID=${requestModel.presOrderID}");
          } catch (e) {
            loggerService.logError("Error processing update HHC order response: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      loggerService.logError("Unknown error in updateHhcPresOrder: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<HospitalsModel>>>> getHospitalsList() async {
    Map<String, dynamic> requestBody = {};

    try {
      GenericApiModel<List<HospitalsModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getHospitalsList,
        isRCService: false, // This uses the base HIS API URL, not RC
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("Get Hospitals List API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<HospitalsModel> hospitalsList = [];

            loggerService.logInfo("Hospitals List Raw Response: $response");

            if (response['ListProject'] != null && response['ListProject'] is List) {
              final projectsList = response['ListProject'] as List;

              for (var projectJson in projectsList) {
                try {
                  if (projectJson is Map<String, dynamic>) {
                    hospitalsList.add(HospitalsModel.fromJson(projectJson));
                  }
                } catch (e) {
                  loggerService.logError('Error parsing hospital item: ${e.toString()}');
                }
              }
            } else {
              loggerService.logInfo('Hospitals list response array is empty or missing');
            }

            apiResponse = GenericApiModel<List<HospitalsModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: hospitalsList,
            );

            loggerService.logInfo("Hospitals fetched successfully: ${hospitalsList.length} hospitals");
          } catch (e) {
            loggerService.logError("Error parsing hospitals list: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      loggerService.logError("Unknown error in getHospitalsList: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<int>>> addCmcOrder({
    required int projectID,
    required int orderServiceID,
    required List<PatientERCMCInsertServicesList> services,
  }) async {
    try {
      GenericApiModel<int>? apiResponse;
      Failure? failure;

      final requestBody = {
        'ProjectID': projectID,
        'OrderServiceID': orderServiceID,
        'procedures': services.map((service) => service.toJson()).toList(),
      };

      await apiClient.post(
        ApiConsts.addCMCOrder,
        isRCService: true,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("Add CMC Order API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          int requestId = 0;
          if (response is Map) {
            requestId = response['response'];
          }
          try {
            apiResponse = GenericApiModel<int>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: requestId,
            );

            loggerService.logInfo("CMC Order added successfully: ProjectID=$projectID, OrderServiceID=$orderServiceID");
          } catch (e) {
            loggerService.logError("Error processing add CMC order response: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      loggerService.logError("Unknown error in addCmcOrder: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<int>>> addHhcOrder({
    required int projectID,
    required int orderServiceID,
    required List<PatientERCMCInsertServicesList> services,
  }) async {
    try {
      GenericApiModel<int>? apiResponse;
      Failure? failure;

      final requestBody = {
        'ProjectID': projectID,
        'OrderServiceID': orderServiceID,
        'procedures': services.map((service) => service.toJson()).toList(),
      };

      await apiClient.post(
        ApiConsts.addHHCOrder,
        isRCService: true,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("Add HHC Order API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          int requestId = 0;
          if (response is Map) {
            requestId = response['response'];
          }
          try {
            apiResponse = GenericApiModel<int>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: requestId,
            );

            loggerService.logInfo("HHC Order added successfully: ProjectID=$projectID, OrderServiceID=$orderServiceID");
          } catch (e) {
            loggerService.logError("Error processing add HHC order response: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      loggerService.logError("Unknown error in addHhcOrder: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }


  /*e-referral functions*/


  @override
  Future<Either<Failure, GenericApiModel<List<GetAllRelationshipTypeResponseModel>>>> getRelationshipTypes() async {
    Map<String, dynamic> requestBody = {};

    try {
      GenericApiModel<List<GetAllRelationshipTypeResponseModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getAllRelationshipTypes,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<GetAllRelationshipTypeResponseModel> relationshipList = [];

            if (response['List_EReferralResult'] != null && response['List_EReferralResult'] is List) {
              final servicesList = response['List_EReferralResult'] as List;

              for (var serviceJson in servicesList) {
                if (serviceJson is Map<String, dynamic>) {
                  relationshipList.add(GetAllRelationshipTypeResponseModel.fromJson(serviceJson));
                }
              }
            }

            apiResponse = GenericApiModel<List<GetAllRelationshipTypeResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: relationshipList,
            );
          } catch (e) {
            loggerService.logError("Error parsing E-Referral services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in getAllCmcServices: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<GetAllCitiesResponseModel>>>> getAllCities() async {
    Map<String, dynamic> requestBody = {};

    try {
      GenericApiModel<List<GetAllCitiesResponseModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getAllCities,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<GetAllCitiesResponseModel> citiesList = [];

            if (response['ListCities'] != null && response['ListCities'] is List) {
              final servicesList = response['ListCities'] as List;

              for (var serviceJson in servicesList) {
                if (serviceJson is Map<String, dynamic>) {
                  citiesList.add(GetAllCitiesResponseModel.fromJson(serviceJson));
                }
              }
            }

            apiResponse = GenericApiModel<List<GetAllCitiesResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: citiesList,
            );
          } catch (e) {
            loggerService.logError("Error parsing E-Referral services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in getAllCmcServices: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }


  @override
  Future<Either<Failure, GenericApiModel<String>>> sendEReferralActivationCode(SendActivationCodeForEReferralRequestModel requestModel) async {
    GenericApiModel<String>? apiResponse;
    try {

      Failure? failure;
      await apiClient.post(
        ApiConsts.sendActivationCodeForEReferral,
        body: requestModel.toJson(),
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {



          apiResponse =   GenericApiModel<String>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: response['LogInTokenID'] as String,
            );
          } catch (e) {
            loggerService.logError("Error parsing E-Referral services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in getAllCmcServices: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<String>>> createEReferral(CreateEReferralRequestModel requestModel) async {
    GenericApiModel<String>? apiResponse;
    try {
      Failure? failure;
      await apiClient.post(
        ApiConsts.createEReferral,
        body: requestModel.toJson(),
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse =   GenericApiModel<String>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data:  response['ReferralNumber'].toString(),
            );
          } catch (e) {
            loggerService.logError("Error parsing E-Referral services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in getAllCmcServices: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }


  @override
  Future<Either<Failure, GenericApiModel<String>>> checkEReferralActivationCode(CheckActivationCodeForEReferralRequestModel requestModel) async {
    GenericApiModel<String>? apiResponse;
    try {
      Failure? failure;
      await apiClient.post(
        ApiConsts.checkActivationCodeForEReferral,
        body: requestModel.toJson(),
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse =   GenericApiModel<String>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: response['IsAuthenticated'].toString(),
            );
          } catch (e) {
            loggerService.logError("Error parsing E-Referral services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in getAllCmcServices: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }



  @override
  Future<Either<Failure, GenericApiModel<List<SearchEReferralResponseModel>>>> searchEReferral(SearchEReferralRequestModel requestBody) async {


    try {
      GenericApiModel<List<SearchEReferralResponseModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        ApiConsts.getEReferrals,
        body: requestBody.toJson(),
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<SearchEReferralResponseModel> searchReferral = [];

            if (response['List_EReferrals'] != null && response['List_EReferrals'] is List) {
              final servicesList = response['List_EReferrals'] as List;

              for (var serviceJson in servicesList) {
                if (serviceJson is Map<String, dynamic>) {
                  searchReferral.add(SearchEReferralResponseModel.fromJson(serviceJson));
                }
              }
            }

            apiResponse = GenericApiModel<List<SearchEReferralResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: searchReferral,
            );
          } catch (e) {
            loggerService.logError("Error parsing E-Referral services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in Search Referral: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }


  @override
  Future<Either<Failure, GenericApiModel<List<Covid19GetTestProceduresResp>>>> getCovidTestProcedures() async {

    try {
      GenericApiModel<List<Covid19GetTestProceduresResp>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        GET_COVID_DRIVETHRU_PROCEDURES_LIST,
        body: {"TestTypeEnum":2,"TestProcedureEnum":3,},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("Covid Test Procedure : $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<Covid19GetTestProceduresResp> covidTestProcedure = [];

            if (response['COVID19_TestProceduresList'] != null && response['COVID19_TestProceduresList'] is List) {
              final servicesList = response['COVID19_TestProceduresList'] as List;

              for (var serviceJson in servicesList) {
                if (serviceJson is Map<String, dynamic>) {
                  covidTestProcedure.add(Covid19GetTestProceduresResp.fromJson(serviceJson));
                }
              }
            }

            apiResponse = GenericApiModel<List<Covid19GetTestProceduresResp>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: covidTestProcedure,
            );
          } catch (e) {
            loggerService.logError("Error parsing E-Referral services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in Search Referral: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<Covid19GetPaymentInfo>>> getCovidPaymentInfo(String procedureID, int projectID) async {

    try {
      GenericApiModel<Covid19GetPaymentInfo>? apiResponse;
      Failure? failure;

      await apiClient.post(
        GET_COVID_DRIVETHRU_PAYMENT_INFO,
        body: {"TestTypeEnum":2,"TestProcedureEnum":3, "ProcedureId":procedureID, "ProjectID":projectID,},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("Covid Test Procedure : $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {

            Covid19GetPaymentInfo    covidPaymentInfo =   Covid19GetPaymentInfo.fromJson(response["COVID19_PatientShare"]);


            apiResponse = GenericApiModel<Covid19GetPaymentInfo>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: covidPaymentInfo,
            );
          } catch (e) {
            loggerService.logError("Error parsing E-Referral services: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in Search Referral: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<VitalSignResModel>>>> getPatientVitalSign() async {
    Map<String, dynamic> requestBody = {
    };

    try {
      GenericApiModel<List<VitalSignResModel>>? apiResponse;
      Failure? failure;

      await apiClient.post(
        GET_PATIENT_VITAL_SIGN,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
          loggerService.logError("Patient Vital Sign API Failed: $error, Status: $statusCode");
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            List<VitalSignResModel> vitalSignList = [];

            if (response['List_DoctorPatientVitalSign'] != null && response['List_DoctorPatientVitalSign'] is List) {
              final vitalSignsList = response['List_DoctorPatientVitalSign'] as List;

              for (var vitalSignJson in vitalSignsList) {
                if (vitalSignJson is Map<String, dynamic>) {
                  final vitalSign = VitalSignResModel.fromJson(vitalSignJson);

                  // Debug logging for blood pressure
                  // print('=== Repository Blood Pressure Check ===');
                  // print('bloodPressureHigher: ${vitalSign.bloodPressureHigher}');
                  // print('bloodPressureLower: ${vitalSign.bloodPressureLower}');
                  // print('weightKg: ${vitalSign.weightKg}');
                  // print('heightCm: ${vitalSign.heightCm}');

                  // Check if the record has at least one valid vital sign measurement
                  final hasValidWeight = _isValidValue(vitalSign.weightKg);
                  final hasValidHeight = _isValidValue(vitalSign.heightCm);
                  final hasValidBMI = _isValidValue(vitalSign.bodyMassIndex);
                  final hasValidTemperature = _isValidValue(vitalSign.temperatureCelcius);
                  final hasValidHeartRate = _isValidValue(vitalSign.heartRate) || _isValidValue(vitalSign.pulseBeatPerMinute);
                  final hasValidRespiration = _isValidValue(vitalSign.respirationBeatPerMinute);
                  final hasValidBloodPressure = _isValidValue(vitalSign.bloodPressureHigher) || _isValidValue(vitalSign.bloodPressureLower);

                  // print('hasValidBloodPressure: $hasValidBloodPressure');
                  // print('Will add to list: ${hasValidWeight || hasValidHeight || hasValidBMI || hasValidTemperature || hasValidHeartRate || hasValidRespiration || hasValidBloodPressure}');
                  // print('=====================================');

                  // Add if ANY vital sign has valid data
                  if (hasValidWeight || hasValidHeight || hasValidBMI || hasValidTemperature ||
                      hasValidHeartRate || hasValidRespiration || hasValidBloodPressure) {
                    vitalSignList.add(vitalSign);
                  }
                }
              }
            }

            apiResponse = GenericApiModel<List<VitalSignResModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: vitalSignList,
            );
          } catch (e) {
            loggerService.logError("Error parsing Patient Vital Sign: ${e.toString()}");
            failure = DataParsingFailure(e.toString());
          }
        },
      );

      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      log("Unknown error in getPatientVitalSign: ${e.toString()}");
      return Left(UnknownFailure(e.toString()));
    }
  }

  /// Helper method to check if a value is valid (greater than 0)
  bool _isValidValue(dynamic value) {
    if (value == null) return false;

    if (value is num) {
      return value > 0;
    }

    if (value is String) {
      if (value.trim().isEmpty) return false;
      final parsed = double.tryParse(value);
      return parsed != null && parsed > 0;
    }

    return false;
  }


}
