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/habib_wallet/models/patient_advance_balance_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

abstract class HabibWalletRepo {
  Future<Either<Failure, GenericApiModel<dynamic>>> getPatientBalanceAmount();

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

  Future<Either<Failure, GenericApiModel<dynamic>>> HISCreateAdvancePayment(
      {required String paymentMethodName, required num paidAmount, required String paymentReference, required String patientID, required int projectID, required String depositorName});

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

  Future<Either<Failure, GenericApiModel<dynamic>>> getPatientInfoByPatientID({required String patientID});

  Future<Either<Failure, GenericApiModel<dynamic>>> getLakumAccountInformation({required String identificationNumber});

  Future<Either<Failure, GenericApiModel<dynamic>>> getLakumAccountInquiryInformation({required String lakumAccountNumber});
}

class HabibWalletRepoImp implements HabibWalletRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

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

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

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

            for (var element in balanceAmountList) {
              element.totalAmount = response['TotalAdvanceBalanceAmount'];
            }

            apiResponse = GenericApiModel<dynamic>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: balanceAmountList,
            );
          } 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<HospitalsModel>>>> getProjectList() async {
    Map<String, dynamic> request = {"IsOnlineCheckIn": true, "IsAdvancePayment": true};

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

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

            apiResponse = GenericApiModel<List<HospitalsModel>>(
              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>> HISCreateAdvancePayment(
      {required String paymentMethodName, required num paidAmount, required String paymentReference, required String patientID, required int projectID, required String depositorName}) async {
    Map<String, dynamic> request = {
      "CustName": depositorName,
      "CustID": patientID,
      "SetupID": "010266",
      "ProjectID": projectID,
      "PatientID": patientID,
      "AccountID": patientID,
      "PaymentAmount": paidAmount,
      "NationalityID": null,
      "DepositorName": depositorName,
      "CreatedBy": 3,
      "PaymentMethodName": paymentMethodName,
      "PaymentReference": paymentReference,
      "PaymentMethod": paymentMethodName,
      "IsAncillaryOrder": false
    };

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

    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>> getPatientInfoByPatientID({required String patientID}) async {
    Map<String, dynamic> requestBody = {"SearchPatientID": patientID};

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_PATIENT_INFO_BY_ID,
        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>> getLakumAccountInformation({required String identificationNumber}) async {
    Map<String, dynamic> requestBody = {"IdentificationNo": identificationNumber};

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_LACUM_ACCOUNT_INFORMATION,
        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>> getLakumAccountInquiryInformation({required String lakumAccountNumber}) async {
    Map<String, dynamic> requestBody = {
      "AccountNumber": lakumAccountNumber,
      "IsDetailsRequired": true,
    };

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