import 'dart:io';

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/cache_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/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_favorite_doctors_list.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/appointment_parking_QR_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/appointment_rated_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/rate_appointment_resp_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/ask_doctor_request_type_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/get_tamara_installments_details_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/features/my_appointments/models/resp_models/patient_appointment_share_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_queue_details_response_model.dart';
import 'package:hmg_patient_app_new/features/my_invoices/models/get_invoices_list_response_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

import 'models/req_model/appointment_rate_req_model.dart';
import 'models/resp_models/appointment_details_resp_model.dart';

abstract class MyAppointmentsRepo {
  Future<Either<Failure, GenericApiModel<List<PatientAppointmentHistoryResponseModel>>>> getPatientAppointments(
      {required bool isActiveAppointment, required bool isArrivedAppointments, bool isForEyeMeasurement = false, bool isForTimeLine = false});

  Future<Either<Failure, GenericApiModel<PatientAppointmentShareResponseModel>>> getPatientShareAppointment(
      {required int projectID, required int clinicID, required String appointmentNo, required bool isLiveCareAppointment});

  Future<Either<Failure, GenericApiModel<dynamic>>> createAdvancePayment(
      {required String paymentMethodName,
      required int projectID,
      required int clinicID,
      required String appointmentNo,
      required num payedAmount,
      required String paymentReference,
      required String patientID,
      required int patientType});

  Future<Either<Failure, GenericApiModel<dynamic>>> addAdvanceNumberRequest({required String advanceNumber, required String paymentReference, required String appointmentNo});

  Future<Either<Failure, GenericApiModel<dynamic>>> generateAppointmentQR({required int clinicID, required int projectID, required String appointmentNo, required int isFollowUp});

  Future<Either<Failure, GenericApiModel<dynamic>>> cancelAppointment({required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel});

  Future<Either<Failure, GenericApiModel<dynamic>>> confirmAppointment({required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel});

  Future<Either<Failure, GenericApiModel<dynamic>>> sendCheckInNfcRequest(
      {required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel, required String scannedCode, required int checkInType});

  Future<Either<Failure, GenericApiModel<List<PatientAppointmentHistoryResponseModel>>>> getPatientAppointmentsForTimeLine();

  Future<Either<Failure, GenericApiModel<List<PatientAppointmentHistoryResponseModel>>>> getPatientDoctorsList({bool isTop8 = false});

  Future<Either<Failure, GenericApiModel<List<GetFavoriteDoctorsListModel>>>> getFavouriteDoctorsList();

  Future<Either<Failure, GenericApiModel<dynamic>>> insertLiveCareVIDARequest({required clientRequestID, required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel});

  Future<Either<Failure, GenericApiModel<GetTamaraInstallmentsDetailsResponseModel>>> getTamaraInstallmentsDetails();

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

  Future<Either<Failure, GenericApiModel<List<AskDocRequestType>>>> getAskDoctorRequestTypes();

  Future<Either<Failure, GenericApiModel<dynamic>>> isDoctorAvailable({required int projectID, required int clinicID, required int doctorID});

  Future<Either<Failure, GenericApiModel<dynamic>>> sendAskDocCallRequest(
      {required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel, required String requestType, required String remarks, required String userMobileNumber});

  Future<Either<Failure, GenericApiModel<List<RateAppointmentRespModel>>>> getLastRatingAppointment();

  Future<Either<Failure, GenericApiModel<AppointmentDetails>>> getAppointmentDetails(int appointmentID, int projectID);

  Future<Either<Failure, GenericApiModel<void>>> sendAppointmentRate(int rate, int appointmentNo, int projectID, int doctorID, int clinicID, String note);

  Future<Either<Failure, GenericApiModel<void>>> sendDoctorRate(
      int rate, int appointmentNo, int projectID, int doctorID, int clinicID, String note, String appoDate, String docName, String projectName, String clinicName);

  Future<Either<Failure, GenericApiModel<PatientQueueDetails>>> getPatientAppointmentQueueDetails({required int appointmentNo, required int patientID, required int clinicID});

  Future<Either<Failure, GenericApiModel<dynamic>>> convertPatientToCash({required int projectID});

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

  Future<Either<Failure, GenericApiModel<dynamic>>> getDoctorsRatingCheck({
    required int doctorID,
    required int projectID,
    required int clinicID,
    required int appointmentNo,
  });

  Future<Either<Failure, GenericApiModel<List<GetInvoicesListResponseModel>>>> getAppointmentInvoice(num appointmentNum);

  Future<Either<Failure, GenericApiModel<AppointmentParkingQRResponseModel>>> getParkingQR(num appointmentNum, int projectID);
}

class MyAppointmentsRepoImp implements MyAppointmentsRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

  @override
  Future<Either<Failure, GenericApiModel<List<PatientAppointmentHistoryResponseModel>>>> getPatientAppointments(
      {required bool isActiveAppointment, required bool isArrivedAppointments, bool isForEyeMeasurement = false, bool isForTimeLine = false}) async {
    Map<String, dynamic> mapDevice = {
      "IsActiveAppointment": isActiveAppointment,
      "IsComingFromCOC": false,
      "isForUpcomming": false,
      "IsForMedicalReport": false,
      "IsForArrived": isArrivedAppointments,
      "IsIrisPrescription": isForEyeMeasurement,
      "IsForTimeLine": isForTimeLine
    };

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

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

            apiResponse = GenericApiModel<List<PatientAppointmentHistoryResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: appointmentsList,
            );
          } 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<PatientAppointmentShareResponseModel>>> getPatientShareAppointment(
      {required int projectID, required int clinicID, required String appointmentNo, required bool isLiveCareAppointment}) async {
    Map<String, dynamic> mapRequest = {"ProjectID": projectID, "ClinicID": clinicID, "AppointmentNo": appointmentNo, "IsActiveAppointment": true, "IsForLiveCare": isLiveCareAppointment};

    late PatientAppointmentShareResponseModel patientShareObj;

    try {
      GenericApiModel<PatientAppointmentShareResponseModel>? apiResponse;
      Failure? failure;
      await apiClient.post(
        isLiveCareAppointment ? GET_PATIENT_SHARE_LIVECARE : GET_PATIENT_SHARE,
        body: mapRequest,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['OnlineCheckInAppointments'];
            patientShareObj = (list == null || list.isEmpty) ? PatientAppointmentShareResponseModel() : PatientAppointmentShareResponseModel.fromJson(list[0]);
            patientShareObj.isCash = isLiveCareAppointment ? list[0]["IsCash"] : response["IsCash"];
            patientShareObj.isEligible = isLiveCareAppointment ? list[0]["IsEligible"] : response["IsEligible"];
            patientShareObj.isInsured = isLiveCareAppointment ? list[0]["IsInsured"] : response["IsInsured"];

            // if (list == null || list.isEmpty) {
            //   throw Exception("patient share list is empty");
            // }

            // final patientShareObj = PatientAppointmentShareResponseModel.fromJson(list[0]);
            // patientShareObj.isCash = response["IsCash"];
            // patientShareObj.isEligible = response["IsEligible"];
            // patientShareObj.isInsured = response["IsInsured"];

            apiResponse = GenericApiModel<PatientAppointmentShareResponseModel>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: patientShareObj,
            );
          } 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>> createAdvancePayment({
    required String paymentMethodName,
    required int projectID,
    required int clinicID,
    required String appointmentNo,
    required num payedAmount,
    required String paymentReference,
    required String patientID,
    required int patientType,
  }) async {
    Map<String, dynamic> requestBody = {
      "ProjectID": projectID,
      "OnlineCheckInAppointment": {
        "AppointmentNo": appointmentNo,
        "PaymentMethodName": paymentMethodName,
        "PaymentAmount": payedAmount == 0 ? "0" : payedAmount.toString(),
        "PaymentDate": payedAmount == 0 ? "" : "/Date(${DateTime.now().millisecondsSinceEpoch})/",
        "PaymentReferenceNumber": payedAmount == 0 ? "" : paymentReference,
        "ProjectID": projectID,
        "PatientID": patientID,
        "ClinicID": clinicID,
        "UserID": patientID,
        "Status": patientType
      }
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        CREATE_ADVANCE_PAYMENT,
        body: requestBody,
        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>> addAdvanceNumberRequest({required String advanceNumber, required String paymentReference, required String appointmentNo}) async {
    Map<String, dynamic> requestBody = {
      "AdvanceNumber": advanceNumber,
      "AdvanceNumber_VP": advanceNumber,
      "PaymentReferenceNumber": paymentReference,
      "AppointmentID": appointmentNo,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ADD_ADVANCE_NUMBER_REQUEST,
        body: requestBody,
        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>> generateAppointmentQR({required int clinicID, required int projectID, required String appointmentNo, required int isFollowUp}) async {
    Map<String, dynamic> requestBody = {
      "AppointmentNo": appointmentNo,
      "ClinicID": clinicID,
      "ProjectID": projectID,
      "IsFollowup": isFollowUp,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GENERATE_QR_APPOINTMENT,
        body: requestBody,
        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>> cancelAppointment({required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel}) async {
    Map<String, dynamic> requestBody = {
      "AppointmentID": patientAppointmentHistoryResponseModel.appointmentNo,
      "ClinicID": patientAppointmentHistoryResponseModel.clinicID,
      "ProjectID": patientAppointmentHistoryResponseModel.projectID,
      "CancelToReschadual": false,
      "EndTime": patientAppointmentHistoryResponseModel.endTime,
      "StartTime": patientAppointmentHistoryResponseModel.startTime,
      "DoctorID": patientAppointmentHistoryResponseModel.doctorID,
      "IsForLiveCare": patientAppointmentHistoryResponseModel.isLiveCareAppointment,
      "OriginalClinicID": patientAppointmentHistoryResponseModel.originalClinicID,
      "OriginalProjectID": patientAppointmentHistoryResponseModel.originalProjectID
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        CANCEL_APPOINTMENT,
        body: requestBody,
        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>> confirmAppointment({required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel}) async {
    Map<String, dynamic> requestBody = {
      "AppointmentNumber": patientAppointmentHistoryResponseModel.appointmentNo,
      "IsLiveCareAppointment": patientAppointmentHistoryResponseModel.isLiveCareAppointment,
      "ClinicID": patientAppointmentHistoryResponseModel.clinicID,
      "ProjectID": patientAppointmentHistoryResponseModel.projectID,
      "ConfirmationBy": 102,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        CONFIRM_APPOINTMENT,
        body: requestBody,
        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>> sendCheckInNfcRequest(
      {required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel, required String scannedCode, required int checkInType}) async {
    Map<String, dynamic> requestBody = {
      "AppointmentNo": patientAppointmentHistoryResponseModel.appointmentNo,
      "NFC_Code": scannedCode,
      "ProjectID": patientAppointmentHistoryResponseModel.projectID,
      "ClinicID": patientAppointmentHistoryResponseModel.clinicID,
      "CheckinBy": checkInType,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        SEND_CHECK_IN_NFC_REQUEST,
        body: requestBody,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: response,
            );
          } catch (e) {
            failure = DataParsingFailure(e.toString());
          }
        },
        isAllowAny: true,
      );
      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<PatientAppointmentHistoryResponseModel>>>> getPatientAppointmentsForTimeLine() async {
    Map<String, dynamic> mapDevice = {
      "isDentalAllowedBackend": false,
      "PatientTypeID": 1,
      "IsComingFromCOC": false,
      "PatientType": 1,
      "IsForTimeLine": true,
    };

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

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

            apiResponse = GenericApiModel<List<PatientAppointmentHistoryResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: appointmentsList,
            );
          } 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<PatientAppointmentHistoryResponseModel>>>> getPatientDoctorsList({bool isTop8 = false}) async {
    Map<String, dynamic> mapDevice = {
      "Top": 0,
      "beforeDays": 0,
      "exludType": 4,
      "IsTop8": isTop8,
    };

    try {
      GenericApiModel<List<PatientAppointmentHistoryResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_MY_DOCTOR,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['PatientDoctorAppointmentResultList'];

            List<PatientAppointmentHistoryResponseModel> appointmentsList =
                list.map((item) => PatientAppointmentHistoryResponseModel.fromJson(item as Map<String, dynamic>)).toList().cast<PatientAppointmentHistoryResponseModel>();

            // appointmentsList.removeWhere((element) => element.isActiveDoctorProfile == false);

            apiResponse = GenericApiModel<List<PatientAppointmentHistoryResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: appointmentsList,
            );
          } 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<GetFavoriteDoctorsListModel>>>> getFavouriteDoctorsList() async {
    Map<String, dynamic> mapDevice = {};

    try {
      GenericApiModel<List<GetFavoriteDoctorsListModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_FAVOURITE_DOCTOR,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['Patient_GetFavouriteDoctorList'];

            if (list == null || list.isEmpty) {
              apiResponse = GenericApiModel<List<GetFavoriteDoctorsListModel>>(
                messageStatus: messageStatus,
                statusCode: statusCode,
                errorMessage: null,
                data: [],
              );
              return;
            }

            final appointmentsList = (list as List).map((item) => GetFavoriteDoctorsListModel.fromJson(item as Map<String, dynamic>)).toList().cast<GetFavoriteDoctorsListModel>();

            appointmentsList.removeWhere((element) => element.isActive == false);

            apiResponse = GenericApiModel<List<GetFavoriteDoctorsListModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: appointmentsList,
            );
          } 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>> insertLiveCareVIDARequest({required clientRequestID, required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel}) async {
    Map<String, dynamic> requestBody = {
      "AppointmentNo": patientAppointmentHistoryResponseModel.appointmentNo,
      "AppointmentDate": patientAppointmentHistoryResponseModel.appointmentDate,
      "ClientRequestID": clientRequestID,
      "ClinicID": patientAppointmentHistoryResponseModel.clinicID,
      "ProjectID": patientAppointmentHistoryResponseModel.projectID,
      "ServiceID": patientAppointmentHistoryResponseModel.serviceID,
      "AcceptedBy": patientAppointmentHistoryResponseModel.doctorID,
      "IsFlutter": true,
      "DeviceToken": await Utils.getStringFromPrefs(CacheConst.pushToken),
      "VoipToken": "", // TODO: Add VoIP Token functionality
      "IsVoip": Platform.isIOS ? true : false
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        INSERT_VIDA_REQUEST,
        body: requestBody,
        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<GetTamaraInstallmentsDetailsResponseModel>>> getTamaraInstallmentsDetails() async {
    try {
      GenericApiModel<GetTamaraInstallmentsDetailsResponseModel>? apiResponse;
      Failure? failure;
      await apiClient.get(
        ApiConsts.GET_TAMARA_INSTALLMENTS_URL,
        isExternal: true,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response;

            final tamaraInstallmentsList = GetTamaraInstallmentsDetailsResponseModel.fromJson(list.first);

            apiResponse = GenericApiModel<GetTamaraInstallmentsDetailsResponseModel>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: tamaraInstallmentsList,
            );
          } 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>> getActiveAppointmentsCount() async {
    Map<String, dynamic> mapDevice = {};

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_ACTIVE_APPOINTMENTS_LIST_URL,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final appointmentCount = response['AppointmentActiveNumber'];

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: appointmentCount,
            );
          } 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>> isDoctorAvailable({required int projectID, required int clinicID, required int doctorID}) async {
    Map<String, dynamic> mapDevice = {"isDentalAllowedBackend": false, "DoctorID": doctorID, "ProjectID": projectID, "ClinicID": clinicID};

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        IS_DOCTOR_AVAILABLE_BY_CALENDAR_SCHEDULE,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final isDoctorAvailable = response['IsDoctorAvailable'];

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: isDoctorAvailable,
            );
          } 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<AskDocRequestType>>>> getAskDoctorRequestTypes() async {
    Map<String, dynamic> mapDevice = {};
    try {
      GenericApiModel<List<AskDocRequestType>>? apiResponse;
      Failure? failure;
      await apiClient.post(GET_CALL_REQUEST_TYPE, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          final list = response['ListReqTypes'];

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

          apiResponse = GenericApiModel<List<AskDocRequestType>>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: askDoctorRequestTypesList,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: mapDevice);
      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>> sendAskDocCallRequest(
      {required PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel, required String requestType, required String remarks, required String userMobileNumber}) async {
    Map<String, dynamic> body = {};

    body['ProjectID'] = patientAppointmentHistoryResponseModel.projectID;
    body['SetupID'] = patientAppointmentHistoryResponseModel.setupID;
    body['DoctorID'] = patientAppointmentHistoryResponseModel.doctorID;
    body['PatientMobileNumber'] = userMobileNumber;
    body['IsMessageSent'] = false;
    body['RequestDate'] = DateUtil.convertDateToString(DateTime.now());
    body['RequestTime'] = DateUtil.convertDateToString(DateTime.now());
    body['Remarks'] = remarks;
    body['Status'] = 2; // 4 for testing only.."cancelled status insert" else should be changed to 1 in live version
    body['CreatedBy'] = 102;
    body['CreatedOn'] = DateUtil.convertDateToString(DateTime.now());
    body['EditedBy'] = 102;
    body['EditedOn'] = DateUtil.convertDateToString(DateTime.now());
    body['isDentalAllowedBackend'] = false;
    body['AppointmentNo'] = patientAppointmentHistoryResponseModel.appointmentNo;
    body['ClinicID'] = patientAppointmentHistoryResponseModel.clinicID;
    body['QuestionType'] = num.parse(requestType);
    body['RequestType'] = num.parse(requestType);
    body['RequestTypeID'] = num.parse(requestType);

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(INSERT_CALL_INFO, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          apiResponse = GenericApiModel<dynamic>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: true,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: body);
      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<PatientQueueDetails>>> getPatientAppointmentQueueDetails({required int appointmentNo, required int patientID, required int clinicID}) async {
    Map<String, dynamic> mapDevice = {"appointmentNo": appointmentNo, "patientID": patientID, "clinicID": clinicID, "apiKey": "EE17D21C7943485D9780223CCE55DCE5"};
    try {
      GenericApiModel<PatientQueueDetails>? apiResponse;
      Failure? failure;
      await apiClient.post(ApiConsts.QLINE_URL, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          // final list = response['data'];
          final queueData = response;
          // final queueList = list.map((item) => PatientQueueDetails.fromJson(item as Map<String, dynamic>)).toList().cast<PatientQueueDetails>();
          final queueList = PatientQueueDetails.fromJson(queueData);

          // queueList.patientQueueData!.isClinicConfigured = 1;

          apiResponse = GenericApiModel<PatientQueueDetails>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: queueList,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: mapDevice, isExternal: true, isAllowAny: true);
      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<RateAppointmentRespModel>>>> getLastRatingAppointment() async {
    Map<String, dynamic> mapDevice = {};
    try {
      GenericApiModel<List<RateAppointmentRespModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(IS_LAST_APPOITMENT_RATED, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          final list = response['IsLastAppoitmentRatedList'];

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

          apiResponse = GenericApiModel<List<RateAppointmentRespModel>>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: lstRatingAppointmentList,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: mapDevice);
      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<AppointmentDetails>>> getAppointmentDetails(int appointmentID, int projectID) async {
    Map<String, dynamic> mapDevice = {
      "AppointmentNumber": appointmentID,
      "ProjectID": projectID,
    };
    try {
      GenericApiModel<AppointmentDetails>? apiResponse;
      Failure? failure;
      await apiClient.post(GET_APPOINTMENT_DETAILS_BY_NO, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          final list = response['AppointmentDetails'];

          final appointmentDetails = AppointmentDetails.fromJson(list);

          apiResponse = GenericApiModel<AppointmentDetails>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: appointmentDetails,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: mapDevice);
      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<void>>> sendAppointmentRate(int rate, int appointmentNo, int projectID, int doctorID, int clinicID, String note) async {
    AppointmentRate appointmentRate = AppointmentRate();
    appointmentRate.rate = rate;
    appointmentRate.appointmentNo = appointmentNo;
    appointmentRate.projectID = projectID;
    appointmentRate.doctorID = doctorID;
    appointmentRate.clinicID = clinicID;
    appointmentRate.note = note;
    appointmentRate.createdBy = 2;
    appointmentRate.editedBy = 2;

    try {
      GenericApiModel<bool>? apiResponse;
      Failure? failure;
      await apiClient.post(NEW_RATE_APPOINTMENT_URL, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          final list = response['AppointmentRated'];

          apiResponse = GenericApiModel<bool>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: list,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: appointmentRate.toJson());
      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<void>>> sendDoctorRate(
      int rate, int appointmentNo, int projectID, int doctorID, int clinicID, String note, String appoDate, String docName, String projectName, String clinicName) async {
    Map<String, dynamic> request;

    request = {
      "DoctorID": doctorID,
      "Rate": rate,
      "ClinicID": clinicID,
      "ProjectID": projectID,
      "AppointmentNo": appointmentNo,
      "Note": note,
      // "MobileNumber": authenticatedUserObject.user!.mobileNumber,
      "AppointmentDate": appoDate,
      "DoctorName": docName,
      "ProjectName": projectName,
      "COCTypeName": 1,
      // "PatientName": authenticatedUserObject.user!.firstName! + " " + authenticatedUserObject.user!.lastName!,
      // "PatientOutSA": authenticatedUserObject.user!.outSA,
      // "PatientTypeID": authenticatedUserObject.user!.patientType,
      "ClinicName": clinicName,
      // "PatientIdentificationID": authenticatedUserObject.user!.patientIdentificationNo
    };

    try {
      GenericApiModel<bool>? apiResponse;
      Failure? failure;
      await apiClient.post(NEW_RATE_DOCTOR_URL, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          final list = response['AppointmentRated'];

          // final appointmentDetails = AppointmentDetails.fromJson(list);

          apiResponse = GenericApiModel<bool>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: list,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: request);
      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>> convertPatientToCash({required int projectID}) async {
    Map<String, dynamic> request;

    request = {"ProjectID": projectID};

    try {
      GenericApiModel<bool>? apiResponse;
      Failure? failure;
      await apiClient.post(CONVERT_PATIENT_TO_CASH, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          final list = (response['MessageStatus'] == 1);

          apiResponse = GenericApiModel<bool>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: list,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: request);
      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>> sendPatientUpdateRequest() async {
    Map<String, dynamic> request = {};

    try {
      GenericApiModel<bool>? apiResponse;
      Failure? failure;
      await apiClient.post(SEND_PATIENT_IMMEDIATE_UPDATE_INSURANCE_REQUEST, onFailure: (error, statusCode, {messageStatus, failureType}) {
        failure = failureType;
      }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
        try {
          final list = (response['MessageStatus'] == 1);

          apiResponse = GenericApiModel<bool>(
            messageStatus: messageStatus,
            statusCode: statusCode,
            errorMessage: null,
            data: list,
          );
        } catch (e) {
          failure = DataParsingFailure(e.toString());
        }
      }, body: request);
      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<AppointmentRatedResponseModel>>> getDoctorsRatingCheck({
    required int doctorID,
    required int projectID,
    required int clinicID,
    required int appointmentNo,
  }) async {
    Map<String, dynamic> mapDevice = {
      "DoctorID": doctorID,
      "ProjectID": projectID,
      "ClinicID": clinicID,
      "AppointmentNo": appointmentNo,
    };

    try {
      GenericApiModel<AppointmentRatedResponseModel>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_DOCTORS_RATING_CHECK,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            AppointmentRatedResponseModel appointmentRatedResponseModel = AppointmentRatedResponseModel.fromJson(response['DoctorsRatingResponseModel'][0]);

            apiResponse = GenericApiModel<AppointmentRatedResponseModel>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: errorMessage,
              data: appointmentRatedResponseModel,
            );
          } 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<GetInvoicesListResponseModel>>>> getAppointmentInvoice(num appointmentNum) async {
    Map<String, dynamic> mapDevice = {"AppointmentNo": appointmentNum};

    try {
      GenericApiModel<List<GetInvoicesListResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_ALL_APPOINTMENTS_FOR_DENTAL_CLINIC,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['List_AllInvoices'];

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

            apiResponse = GenericApiModel<List<GetInvoicesListResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: invoicesList,
            );
          } 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<AppointmentParkingQRResponseModel>>> getParkingQR(num appointmentNum, int projectID) async {
    Map<String, dynamic> mapDevice = {"AppointmentNo": appointmentNum, "ProjectID": projectID};

    try {
      GenericApiModel<AppointmentParkingQRResponseModel>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_APPOINTMENT_PARKING_QR,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            AppointmentParkingQRResponseModel appointmentParkingQRResponseModel = AppointmentParkingQRResponseModel.fromJson(response['ParkingTicketsForAppointment'][0]);

            apiResponse = GenericApiModel<AppointmentParkingQRResponseModel>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: appointmentParkingQRResponseModel,
            );
          } 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()));
    }
  }
}
