import 'dart:developer';

import 'package:mc_common_app/api/api_client.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.dart';
import 'package:mc_common_app/config/dependency_injection.dart';
import 'package:mc_common_app/models/appointments_models/appointment_list_model.dart';
import 'package:mc_common_app/models/appointments_models/schedule_model.dart';
import 'package:mc_common_app/models/appointments_models/service_schedule_model.dart';
import 'package:mc_common_app/models/general_models/generic_resp_model.dart';
import 'package:mc_common_app/models/general_models/m_response.dart';
import 'package:mc_common_app/models/provider_branches_models/profile/services.dart';

abstract class AppointmentRepo {
  Future<List<AppointmentListModel>> getMyAppointmentsForProvider(Map<String, dynamic> map);

  Future<List<AppointmentListModel>> getMyAppointmentsForCustomersByFilters({
    List<String>? providerIdsList,
    List<String>? categoryIdsList,
    List<String>? serviceIdsList,
    List<String>? branchIdsList,
  });

  Future<MResponse> updateAppointmentStatus(Map<String, dynamic> map);

  Future<MResponse> updateAppointmentPaymentStatus(Map<String, dynamic> map);

  Future<MResponse> getAppointmentSlots(Map<String, dynamic> map);

  Future<MResponse> createMergeAppointment(Map<String, dynamic> map);

  Future<Services> getAllServices(String branchId);

  Future<MResponse> createSchedule(Map map);

  Future<MResponse> addServicesInSchedule(Map map);

  Future<MResponse> updateSchedule(Map map);

  Future<List<ScheduleData>> getSchedules(String branchId);

  Future<MResponse> updateServicesInSchedule(Map map);

  Future<List<ServiceAppointmentScheduleModel>> mergeServiceIntoAvailableSchedules({
    required List<String> serviceItemIdsForHome,
    required List<String> serviceItemIdsForWorkshop,
  });

  Future<GenericRespModel> createServiceAppointment({required List<ServiceAppointmentScheduleModel> schedules, required int serviceProviderID});

  Future<GenericRespModel> cancelOrRescheduleServiceAppointment({required int serviceAppointmentID, required int serviceSlotID, required int appointmentScheduleAction});
}

class AppointmentRepoImp implements AppointmentRepo {
  ApiClient apiClient = injector.get<ApiClient>();
  AppState appState = injector.get<AppState>();

  @override
  Future<Services> getAllServices(String branchId) async {
    Map<String, dynamic> map = {"ProviderBranchID": branchId};
    String t = appState.getUser.data!.accessToken ?? "";
    return await apiClient.getJsonForObject((json) => Services.fromJson(json), ApiConsts.getServicesOfBranch, token: t, queryParameters: map);
  }

  @override
  Future<MResponse> createSchedule(Map map) async {
    String t = appState.getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.createSchedule, map, token: t);
  }

  @override
  Future<MResponse> addServicesInSchedule(Map map) async {
    String t = appState.getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.createGroup, map, token: t);
  }

  @override
  Future<List<ScheduleData>> getSchedules(String branchId) async {
    Map<String, dynamic> map = {"ServiceProviderBranchID": branchId};
    String t = appState.getUser.data!.accessToken ?? "";

    GenericRespModel adsGenericModel = await apiClient.getJsonForObject(
      (json) => GenericRespModel.fromJson(json),
      ApiConsts.getSchedule,
      token: t,
      queryParameters: map,
    );

    return List.generate(adsGenericModel.data.length, (index) => ScheduleData.fromJson(adsGenericModel.data[index]));
  }

  @override
  Future<MResponse> updateSchedule(Map map) async {
    String t = appState.getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.updateSchedule, map, token: t);
  }

  @override
  Future<MResponse> updateServicesInSchedule(Map map) async {
    String t = appState.getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.updateGroup, map, token: t);
  }

  Future<List<ServiceAppointmentScheduleModel>> mergeServiceIntoAvailableSchedules({
    required List<String> serviceItemIdsForHome,
    required List<String> serviceItemIdsForWorkshop,
  }) async {
    String t = appState.getUser.data!.accessToken ?? "";
    var queryParameters = [
      // {
      //   "appointmentType": 2,
      //   "ServiceItemIDs": serviceItemIdsForHome,
      // },
      {
        "appointmentType": 1,
        "ServiceItemIDs": serviceItemIdsForWorkshop,
      }
    ];
    GenericRespModel adsGenericModel = await apiClient.postJsonForObject(
      (json) => GenericRespModel.fromJson(json),
      ApiConsts.GetServiceItemAppointmentScheduleSlots,
      queryParameters,
      token: t,
    );
    if (adsGenericModel.data == null) {
      return [];
    }
    List<ServiceAppointmentScheduleModel> serviceAppointmentScheduleModel =
        List.generate(adsGenericModel.data.length, (index) => ServiceAppointmentScheduleModel.fromJson(adsGenericModel.data[index], isForAppointment: true));
    return serviceAppointmentScheduleModel;
  }

  Future<GenericRespModel> createServiceAppointment({required List<ServiceAppointmentScheduleModel> schedules, required int serviceProviderID}) async {
    String t = appState.getUser.data!.accessToken ?? "";
    int customerId = appState.getUser.data!.userInfo!.customerId ?? 0;

    List<Map<String, dynamic>> mapList = [];
    schedules.forEach((schedule) {
      List<int> serviceItemIds = [];
      schedule.servicesListInAppointment!.forEach((service) {
        service.serviceItems!.forEach((item) {
          serviceItemIds.add(item.id!);
        });
      });
      mapList.add({
        "serviceSlotID": schedule.selectedCustomTimeDateSlotModel!.date!.slotId,
        "serviceProviderID": serviceProviderID,
        "customerID": customerId,
        "serviceItemID": serviceItemIds,
      });
    });
    log("maplist: ${mapList.toString()}");

    GenericRespModel adsGenericModel = await apiClient.postJsonForObject(
      (json) => GenericRespModel.fromJson(json),
      ApiConsts.ServiceProvidersAppointmentCreate,
      mapList,
      token: t,
    );

    return adsGenericModel;
  }

  @override
  Future<GenericRespModel> cancelOrRescheduleServiceAppointment({required int serviceAppointmentID, required int serviceSlotID, required int appointmentScheduleAction}) async {
    String t = appState.getUser.data!.accessToken ?? "";

    final payload = {
      "serviceAppointmentID": serviceAppointmentID,
      "serviceSlotID": serviceSlotID,
      "appointmentScheduleAction": appointmentScheduleAction,
    };

    GenericRespModel adsGenericModel = await apiClient.postJsonForObject(
      (json) => GenericRespModel.fromJson(json),
      ApiConsts.ServiceProviderAppointmentRescheduleCancelAppointment,
      payload,
      token: t,
    );

    return adsGenericModel;
  }

  @override
  Future<List<AppointmentListModel>> getMyAppointmentsForProvider(Map<String, dynamic> map) async {
    String t = appState.getUser.data!.accessToken ?? "";

    GenericRespModel genericRespModel = await apiClient.getJsonForObject(
      token: t,
      (json) => GenericRespModel.fromJson(json),
      queryParameters: map,
      ApiConsts.serviceProvidersAppointmentGet,
    );
    List<AppointmentListModel> appointmentList = List.generate(genericRespModel.data.length, (index) => AppointmentListModel.fromJson(genericRespModel.data[index]));
    return appointmentList;
  }

  @override
  Future<List<AppointmentListModel>> getMyAppointmentsForCustomersByFilters({
    List<String>? providerIdsList,
    List<String>? categoryIdsList,
    List<String>? serviceIdsList,
    List<String>? branchIdsList,
  }) async {
    var params = {
      "customerID": appState.getUser.data!.userInfo!.customerId.toString(),
      "ServiceProviderIDs": providerIdsList ?? [],
      "ProviderBranchIDs": branchIdsList ?? [],
      "ServiceIDs": serviceIdsList ?? [],
      "CategoryIDs": categoryIdsList ?? [],
    };
    GenericRespModel genericRespModel = await apiClient.getJsonForObject(
      token: appState.getUser.data!.accessToken,
      (json) => GenericRespModel.fromJson(json),
      queryParameters: params,
      ApiConsts.customersAppointmentGetByFilters,
    );
    List<AppointmentListModel> appointmentList = List.generate(genericRespModel.data.length, (index) => AppointmentListModel.fromJson(genericRespModel.data[index]));
    return appointmentList;
  }

  @override
  Future<MResponse> getAppointmentSlots(Map<String, dynamic> map) async {
    String t = appState.getUser.data!.accessToken ?? "";

    MResponse adsGenericModel = await apiClient.getJsonForObject(
      (json) => MResponse.fromJson(json),
      ApiConsts.getAppointmentSlots,
      token: t,
      queryParameters: map,
    );

    return adsGenericModel;
  }

  @override
  Future<MResponse> updateAppointmentPaymentStatus(Map<String, dynamic> map) async {
    String t = appState.getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.updateAppointmentPaymentStatus, map, token: t);
  }

  @override
  Future<MResponse> updateAppointmentStatus(Map<String, dynamic> map) async {
    String t = appState.getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.updateAppointmentStatus, map, token: t);
  }

  @override
  Future<MResponse> createMergeAppointment(Map<String, dynamic> map) async {
    String t = appState.getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.createMergeAppointment, map, token: t);
  }
}
