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/insurance/models/resp_models/patient_insurance_approval_response_model.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/patient_insurance_card_history.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/patient_insurance_details_response_model.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/patient_insurance_update_response_model.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/upload_insurance_card_response_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

abstract class InsuranceRepo {
  Future<Either<Failure, GenericApiModel<List<PatientInsuranceDetailsResponseModel>>>> getPatientInsuranceDetails();

  Future<Either<Failure, GenericApiModel<List<PatientInsuranceCardHistoryResponseModel>>>> getPatientInsuranceCardHistory();

  Future<Either<Failure, GenericApiModel<PatientInsuranceUpdateResponseModel>>> getPatientInsuranceDetailsForUpdate({required String patientId, required String identificationNo});

  Future<Either<Failure, GenericApiModel<List<InsuranceApprovalResponseModel>>>> getPatientInsuranceApprovalsList();

  Future<Either<Failure, GenericApiModel<dynamic>>> updatePatientInsuranceCard({
    required int patientID,
    required int patientType,
    required String mobileNo,
    required String patientIdentificationID,
    required String insuranceCardImage,
  });
}

class InsuranceRepoImp implements InsuranceRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

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

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

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

            apiResponse = GenericApiModel<List<PatientInsuranceDetailsResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: labOrders,
            );
          } 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<PatientInsuranceCardHistoryResponseModel>>>> getPatientInsuranceCardHistory() async {
    Map<String, dynamic> mapDevice = {};
    try {
      GenericApiModel<List<PatientInsuranceCardHistoryResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_PAtIENTS_INSURANCE_UPDATED,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['List_PatientInsuranceCardHistory'];
            if (list == null || list.isEmpty) {
              throw Exception("insurance list is empty");
            }

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

            apiResponse = GenericApiModel<List<PatientInsuranceCardHistoryResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: insuranceCardsList,
            );
          } 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<PatientInsuranceUpdateResponseModel>>> getPatientInsuranceDetailsForUpdate({required String patientId, required String identificationNo}) async {
    Map<String, dynamic> mapDevice = {"SetupID": "010266", "ProjectID": 15, "PatientIdentificationID": identificationNo, "IsFamily": false, "ParentID": 0};

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

            final insuranceCardsList = PatientInsuranceUpdateResponseModel.fromJson(list[0]);

            apiResponse = GenericApiModel<PatientInsuranceUpdateResponseModel>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: insuranceCardsList,
            );
          } 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<InsuranceApprovalResponseModel>>>> getPatientInsuranceApprovalsList() async {
    Map<String, dynamic> mapDevice = {};
    try {
      GenericApiModel<List<InsuranceApprovalResponseModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_PAtIENTS_INSURANCE_APPROVALS,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['HIS_Approval_List'];

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

            apiResponse = GenericApiModel<List<InsuranceApprovalResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: insuranceCardsList,
            );
          } 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<dynamic>>> updatePatientInsuranceCard({
    required int patientID,
    required int patientType,
    required String mobileNo,
    required String patientIdentificationID,
    required String insuranceCardImage,
  }) async {
    Map<String, dynamic> mapDevice = {
      "PatientID": patientID,
      "PatientType": patientType,
      "MobileNo": mobileNo,
      "PatientIdentificationID": patientIdentificationID,
      "InsuranceCardImage": insuranceCardImage,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        UPLOAD_INSURANCE_CARD,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            // final uploadResponse = UploadInsuranceCardResponseModel.fromJson(response);

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