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_invoices/models/get_invoice_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/features/my_invoices/models/get_pharmacy_invoices_response_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

abstract class MyInvoicesRepo {
  Future<Either<Failure, GenericApiModel<List<GetInvoicesListResponseModel>>>> getAllInvoicesList();

  Future<Either<Failure, GenericApiModel<List<GetPharmacyInvoicesResponseModel>>>> getAllPharmacyInvoices();

  Future<Either<Failure, GenericApiModel<GetInvoiceDetailsResponseModel>>> getInvoiceDetails({required num appointmentNo, required num invoiceNo, required int projectID});

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

  Future<Either<Failure, GenericApiModel<dynamic>>> downloadInvoice({required String setupId, required int invoiceNo, required int projectID});

  Future<Either<Failure, GenericApiModel<dynamic>>> downloadPharmacyInvoice({required String setupId, required int invoiceNo, required int projectID, required dynamic locationID});
}

class MyInvoicesRepoImp implements MyInvoicesRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

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

    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<List<GetPharmacyInvoicesResponseModel>>>> getAllPharmacyInvoices() async {
    Map<String, dynamic> mapDevice = {};

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

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

            apiResponse = GenericApiModel<List<GetPharmacyInvoicesResponseModel>>(
              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<GetInvoiceDetailsResponseModel>>> getInvoiceDetails({required num appointmentNo, required num invoiceNo, required int projectID}) async {
    Map<String, dynamic> mapDevice = {
      "AppointmentNo": appointmentNo,
      "InvoiceNo": invoiceNo,
      "IsRegistered": true,
      "ProjectID": projectID,
    };

    try {
      GenericApiModel<GetInvoiceDetailsResponseModel>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_DENTAL_APPOINTMENT_INVOICE,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['List_eInvoiceForDental'];
            final invoicesList = GetInvoiceDetailsResponseModel.fromJson(list[0]);

            apiResponse = GenericApiModel<GetInvoiceDetailsResponseModel>(
              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>> sendInvoiceEmail({required num appointmentNo, required int projectID}) async {
    Map<String, dynamic> mapDevice = {
      "AppointmentNo": appointmentNo,
      "IsRegistered": true,
      "ProjectID": projectID,
    };

    try {
      GenericApiModel<GetInvoiceDetailsResponseModel>? apiResponse;
      Failure? failure;
      await apiClient.post(
        SEND_DENTAL_APPOINTMENT_INVOICE_EMAIL,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel(
              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>> downloadInvoice({required String setupId, required int invoiceNo, required int projectID}) async {
    Map<String, dynamic> mapDevice = {
      "SetupID": setupId,
      "ProjectID": projectID,
      "InvoiceNo": invoiceNo,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        DOWNLOAD_INVOICE_PDF,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: response["InvoiceReportPDFContent"],
            );
          } 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>> downloadPharmacyInvoice({required String setupId, required int invoiceNo, required int projectID, required dynamic locationID}) async {
    Map<String, dynamic> mapDevice = {
      "SetupID": setupId,
      "ProjectID": projectID,
      "InvoiceNo": invoiceNo,
      "LocationID": locationID,
    };

    try {
      GenericApiModel<dynamic>? apiResponse;
      Failure? failure;
      await apiClient.post(
        DOWNLOAD_PHARMACY_INVOICE_PDF,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: response["InvoiceReportPDFContent"],
            );
          } 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()));
    }
  }
}
