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/exceptions/api_failure.dart';
import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart';
import 'package:dartz/dartz.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/patient_prescriptions_response_model.dart';
import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/prescription_analysis_response_model.dart';
import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/prescription_delivery_response_model.dart';
import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/prescription_detail_response_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

abstract class PrescriptionsRepo {
  Future<Either<Failure, GenericApiModel<List<PatientPrescriptionsResponseModel>>>> getPatientPrescriptionOrders({required String patientId});

  Future<Either<Failure, GenericApiModel<List<PrescriptionDetailResponseModel>>>> getPatientPrescriptionDetails({required PatientPrescriptionsResponseModel prescriptionsResponseModel});

  Future<Either<Failure, GenericApiModel<dynamic>>> getPrescriptionInstructionsPDF({required PatientPrescriptionsResponseModel prescriptionsResponseModel});

  Future<Either<Failure, GenericApiModel<dynamic>>> getPrescriptionPDF(
      {required PatientPrescriptionsResponseModel prescriptionsResponseModel, required List<PrescriptionDetailResponseModel> prescriptionDetailsList});

  Future<Either<Failure, GenericApiModel<dynamic>>> submitPrescriptionDeliveryRequest(
      {required String latitude, required String longitude, required String appointmentNo, required String dischargeID, required String projectID});

  Future<Either<Failure, GenericApiModel<dynamic>>> getPrescriptionOrdersList();

  Future<Either<Failure, GenericApiModel<PrescriptionAnalysisResponse>>> getPrescriptionAiAnalysis({required dynamic payload, required int langId});
}

class PrescriptionsRepoImp implements PrescriptionsRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

  @override
  Future<Either<Failure, GenericApiModel<List<PatientPrescriptionsResponseModel>>>> getPatientPrescriptionOrders({required String patientId}) async {
    Map<String, dynamic> mapDevice = {};

    try {
      GenericApiModel<List<PatientPrescriptionsResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        PRESCRIPTIONS,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['PatientPrescriptionList'];
            if (list == null || list.isEmpty) {
              // throw Exception("lab list is empty");
            }

            final prescriptionOrders = list.map((item) => PatientPrescriptionsResponseModel.fromJson(item as Map<String, dynamic>)).toList().cast<PatientPrescriptionsResponseModel>();

            apiResponse = GenericApiModel<List<PatientPrescriptionsResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: prescriptionOrders,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<List<PrescriptionDetailResponseModel>>>> getPatientPrescriptionDetails({required PatientPrescriptionsResponseModel prescriptionsResponseModel}) async {
    Map<String, dynamic> mapDevice = {
      "AppointmentNo": prescriptionsResponseModel.appointmentNo.toString(),
      "SetupID": prescriptionsResponseModel.setupID,
      "EpisodeID": prescriptionsResponseModel.episodeID.toString(),
      "ClinicID": prescriptionsResponseModel.clinicID.toString(),
      "ProjectID": prescriptionsResponseModel.projectID.toString(),
      "DischargeNo": prescriptionsResponseModel.dischargeNo.toString()
    };

    try {
      GenericApiModel<List<PrescriptionDetailResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        prescriptionsResponseModel.isInOutPatient! ? GET_PRESCRIPTION_REPORT_ENH : GET_PRESCRIPTION_REPORT,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = prescriptionsResponseModel.isInOutPatient! ? response['ListPRM'] : response['INP_GetPrescriptionReport_List'];
            if (list == null || list.isEmpty) {
              // throw Exception("prescription list is empty");
            }

            final List<PrescriptionDetailResponseModel> prescriptionOrders =
                list.map((item) => PrescriptionDetailResponseModel.fromJson(item as Map<String, dynamic>)).toList().cast<PrescriptionDetailResponseModel>();
            if (prescriptionOrders.isNotEmpty) {
              prescriptionOrders.first.isHomeMedicineDeliverySupported = response['IsHomeMedicineDeliverySupported'] ?? false;
            }

            apiResponse = GenericApiModel<List<PrescriptionDetailResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: prescriptionOrders,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel>> getPrescriptionInstructionsPDF({required PatientPrescriptionsResponseModel prescriptionsResponseModel}) async {
    Map<String, dynamic> mapDevice = {
      "AppointmentNo": prescriptionsResponseModel.appointmentNo.toString(),
      "SetupID": prescriptionsResponseModel.setupID,
      "ClinicID": prescriptionsResponseModel.clinicID.toString(),
      "ProjectID": prescriptionsResponseModel.projectID.toString(),
      "LocationID": "0",
      "SalesInvoiceNo": "0",
      "IsTest": false,
      "ChannelID": "3",
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_PRESCRIPTION_INSTRUCTIONS_PDF,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final prescriptionPDFURL = response["InvoiceUrl"];
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: prescriptionPDFURL,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel>> getPrescriptionPDF(
      {required PatientPrescriptionsResponseModel prescriptionsResponseModel, required List<PrescriptionDetailResponseModel> prescriptionDetailsList}) async {
    // Map<String, dynamic> mapDevice = {
    //   "AppointmentDate": prescriptionsResponseModel.appointmentDate,
    //   "ClinicName": prescriptionsResponseModel.clinicDescription,
    //   "DoctorName": prescriptionsResponseModel.doctorName,
    //   "ProjectID": prescriptionsResponseModel.projectID,
    //   "DoctorID": prescriptionsResponseModel.doctorID,
    //   "ClinicID": prescriptionsResponseModel.clinicID,
    //   "DateofBirth": Utils.appState.getAuthenticatedUser()!.dateofBirth,
    //   "ListPrescriptions": prescriptionDetailsList,
    //   "PatientIditificationNum": Utils.appState.getAuthenticatedUser()!.patientIdentificationNo,
    //   "PatientMobileNumber": Utils.appState.getAuthenticatedUser()!.mobileNumber,
    //   "PatientName": "${Utils.appState.getAuthenticatedUser()!.firstName!} ${Utils.appState.getAuthenticatedUser()!.lastName!}",
    //   "To": Utils.appState.getAuthenticatedUser()!.emailAddress,
    //   "SetupID": prescriptionsResponseModel.setupID,
    //   "IsDownload": true,
    //   "isDentalAllowedBackend": false,
    // };

    Map<String, dynamic> mapDevice = {
      "AppointmentNo": prescriptionsResponseModel.appointmentNo,
      "SetupID": prescriptionsResponseModel.setupID,
      "EpisodeNo": prescriptionsResponseModel.episodeID,
      "ClinicID": prescriptionsResponseModel.clinicID,
      "ProjectID": prescriptionsResponseModel.projectID,
      "DischargeNo": prescriptionsResponseModel.dischargeNo,
      "IsDownload": true,
      "To": Utils.appState.getAuthenticatedUser()!.emailAddress,
      // "To": "amjad.haroon@cloudsolutions.com.sa",
      "ClinicName": prescriptionsResponseModel.clinicDescription,
      "DoctorName": prescriptionsResponseModel.doctorName,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        // SEND_PRESCRIPTION_EMAIL,
        SEND_PRESCRIPTION_EMAIL_NEW,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final prescriptionPDFData = response["Base64Data"];
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: prescriptionPDFData,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel>> submitPrescriptionDeliveryRequest(
      {required String latitude, required String longitude, required String appointmentNo, required String dischargeID, required String projectID}) async {
    Map<String, dynamic> mapDevice = {
      "latitude": latitude,
      "longitude": longitude,
      "AppointmentNo": appointmentNo,
      "DischargeID": dischargeID,
      "ProjectID": projectID,
      "Channel": 3,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        isRCService: true,
        ADD_PRESCRIPTION_ORDER_RC,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: response,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel>> getPrescriptionOrdersList() async {
    Map<String, dynamic> mapDevice = {};

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        isRCService: true,
        GET_ALL_PRESCRIPTION_ORDERS_RC,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {

            final prescriptionOrders = response['response'].map((item) => PrescriptionDeliveryResponseModel.fromJson(item as Map<String, dynamic>)).toList().cast<PrescriptionDeliveryResponseModel>();

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: prescriptionOrders,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }

  @override
  Future<Either<Failure, GenericApiModel<PrescriptionAnalysisResponse>>> getPrescriptionAiAnalysis({required dynamic payload, required int langId}) async {
    try {
      GenericApiModel<PrescriptionAnalysisResponse>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ApiConsts.getAiPrescriptionAnalysis,
        isAllowAny: true,
        isExternal: true,
        apiHeaders: {
          'Accept-Language': 'en-US,en;q=0.7',
          'Content-Type': 'application/json',
          'X-API-KEY': '9d9d2ac4c1fc302299dbb0fbb1b7fea1',
          'accept': 'application/json',
        },
        body: {"medicines": payload, "language_id": langId},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final analysisResponse = PrescriptionAnalysisResponse.fromJson(response);
            apiResponse = GenericApiModel<PrescriptionAnalysisResponse>(
              messageStatus: 1,
              statusCode: statusCode,
              errorMessage: null,
              data: analysisResponse,
            );
          } catch (e) {
            loggerService.logError('Error parsing prescription AI analysis: $e');
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }
}

