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/blood_donation/models/blood_group_hospitals_model.dart';
import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_response_model.dart';
import 'package:hmg_patient_app_new/features/blood_donation/models/cities_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 BloodDonationRepo {
  Future<Either<Failure, GenericApiModel<List<CitiesModel>>>> getAllCities();

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

  Future<Either<Failure, GenericApiModel<List<BdGetProjectsHaveBdClinic>>>> getBloodDonationProjectsList();

  Future<Either<Failure, GenericApiModel<List_BloodGroupDetailsModel>>> getPatientBloodGroupDetails();

  Future<Either<Failure, GenericApiModel<dynamic>>> updateBloodGroup({required Map<String, dynamic> request});

  Future<Either<Failure, GenericApiModel<dynamic>>> getFreeBloodDonationSlots({required Map<String, dynamic> request});

  Future<Either<Failure, GenericApiModel<dynamic>>> addUserAgreementForBloodDonation({required Map<String, dynamic> request});

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

class BloodDonationRepoImp implements BloodDonationRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

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

    try {
      GenericApiModel<List<CitiesModel>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        GET_CITIES_REQUEST,
        body: mapDevice,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['ListCities'];
            final citiesList = list.map((item) => CitiesModel.fromJson(item as Map<String, dynamic>)).toList().cast<CitiesModel>();

            apiResponse = GenericApiModel<List<CitiesModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: citiesList,
            );
          } 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_BloodGroupDetailsModel>>> getPatientBloodGroupDetails() async {
    Map<String, dynamic> mapDevice = {};

    try {
      GenericApiModel<List_BloodGroupDetailsModel>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ApiConsts.getPatientBloodGroup,
        body: mapDevice,
        isAllowAny: true,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final list = response['List_BloodGroupDetails'][0];
            final patientBloodGroup = List_BloodGroupDetailsModel.fromJson(list);

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

    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<List<BdGetProjectsHaveBdClinic>>>> getBloodDonationProjectsList() async {
    Map<String, dynamic> request = {};

    try {
      GenericApiModel<List<BdGetProjectsHaveBdClinic>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ApiConsts.getProjectsHaveBDClinics,
        body: request,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            final listData = (response['BD_getProjectsHaveBDClinics'] as List<dynamic>);
            final list = listData.map((item) => BdGetProjectsHaveBdClinic.fromJson(item as Map<String, dynamic>)).toList();
            apiResponse = GenericApiModel<List<BdGetProjectsHaveBdClinic>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: list,
            );
          } 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<dynamic>>>> updateBloodGroup({required Map<String, dynamic> request}) async {
    try {
      GenericApiModel<List<dynamic>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ApiConsts.bloodGroupUpdate,
        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<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<List<dynamic>>>> getFreeBloodDonationSlots({required Map<String, dynamic> request}) async {
    try {
      GenericApiModel<List<dynamic>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ApiConsts.getClinicsBDFreeSlots,
        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<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<List<dynamic>>>> addUserAgreementForBloodDonation({required Map<String, dynamic> request}) async {
    try {
      GenericApiModel<List<dynamic>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ApiConsts.userAgreementForBloodGroupUpdate,
        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<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<List<dynamic>>>> getUserAgreementForBloodDonation() async {
    try {
      GenericApiModel<List<dynamic>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        ApiConsts.getPatientBloodAgreement,
        body: {},
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            apiResponse = GenericApiModel<List<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()));
    }
  }
}
