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/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/features/ask_doctor/models/ask_doctor_appointments_list.dart';
import 'package:hmg_patient_app_new/features/ask_doctor/models/doctor_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/ask_doctor_request_type_response_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

abstract class AskDoctorRepo {
  Future<Either<Failure, GenericApiModel<List<AskDoctorAppointmentHistoryList>>>> getAskDoctorAppointmentsList();

  Future<Either<Failure, GenericApiModel<List<DoctorResponseModel>>>> getDoctorResponse({
    required String fromDate,
  });
}

class AskDoctorRepoImp implements AskDoctorRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

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

  @override
  Future<Either<Failure, GenericApiModel<List<AskDoctorAppointmentHistoryList>>>> getAskDoctorAppointmentsList() async {
    Map<String, dynamic> mapDevice = {
      "Top": 25,
      "beforeDays": 15,
      "exludType": 4,
    };

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

            final clinicsList = list != null ? list.map((item) => AskDoctorAppointmentHistoryList.fromJson(item as Map<String, dynamic>)).toList().cast<AskDoctorAppointmentHistoryList>() : [];

            apiResponse = GenericApiModel<List<AskDoctorAppointmentHistoryList>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: clinicsList,
            );
          } 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<DoctorResponseModel>>>> getDoctorResponse({
    required String fromDate,
  }) async {
    Map<String, dynamic> mapDevice = {
      "isDentalAllowedBackend": false,
      "from": fromDate,
    };

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

            if (list == null || list.isEmpty) {
              // Return empty list if no responses
              apiResponse = GenericApiModel<List<DoctorResponseModel>>(
                messageStatus: messageStatus,
                statusCode: statusCode,
                errorMessage: null,
                data: [],
              );
              return;
            }

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

            apiResponse = GenericApiModel<List<DoctorResponseModel>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: doctorResponsesList,
            );
          } 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) {
      loggerService.logError("AskDoctorRepo.getDoctorResponse error: $e");
      return Left(UnknownFailure(e.toString()));
    }
  }
}
