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/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 String patientId, required bool isActiveAppointment, required bool isArrivedAppointments});

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

  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 String clinicID, required String projectID, required String appointmentNo, required int isFollowUp});
}

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 String patientId, required bool isActiveAppointment, required bool isArrivedAppointments}) async {
    final mapDevice = {
      "IsActiveAppointment": isActiveAppointment,
      "isDentalAllowedBackend": false,
      "PatientTypeID": 1,
      "IsComingFromCOC": false,
      "PatientType": 1,
      "isForUpcomming": false,
      "IsForArrived": isArrivedAppointments,
      "PatientOutSA": 0
    };

    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 String patientId, required int projectID, required int clinicID, required String appointmentNo}) async {
    final mapRequest = {
      "ProjectID": projectID,
      "ClinicID": clinicID,
      "AppointmentNo": appointmentNo,
      "IsActiveAppointment": true,
      "PatientOutSA": 0,
      "isDentalAllowedBackend": false,
      "PatientID": patientId,
      "PatientTypeID": 1,
      "PatientType": 1,
    };

    try {
      GenericApiModel<PatientAppointmentShareResponseModel>? apiResponse;
      Failure? failure;
      await apiClient.post(
        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()));
    }

    throw UnimplementedError();
  }

  @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 {
    final 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 {
    final 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 String clinicID, required String projectID, required String appointmentNo, required int isFollowUp}) async {
    final 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()));
    }
  }
}
