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/utils.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/hospital_model.dart' show HospitalsModel;
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/services/logger_service.dart';

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

  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();

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

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

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

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}) async {
    Map<String, dynamic> mapDevice = {
      "IsActiveAppointment": isActiveAppointment,
      "IsComingFromCOC": false,
      "isForUpcomming": false,
      "IsForMedicalReport": false,
      "IsForArrived": isArrivedAppointments,
    };

    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};

    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'];
            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() async {
    Map<String, dynamic> mapDevice = {
      "Top": 0,
      "beforeDays": 0,
      "exludType": 4,
    };

    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'];

            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>> 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()));
    }
  }
}
