import 'dart:async';
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/general_models/generic_resp_model.dart';
import 'package:mc_common_app/models/general_models/m_response.dart';

import 'package:flutter/cupertino.dart';
import 'package:mc_common_app/models/provider_branches_models/branch_detail_model.dart';
import 'package:mc_common_app/models/provider_branches_models/profile/branch.dart';
import 'package:mc_common_app/models/provider_branches_models/profile/categroy.dart';
import 'package:mc_common_app/models/provider_branches_models/profile/document.dart';
import 'package:mc_common_app/models/provider_branches_models/profile/services.dart';
import 'package:mc_common_app/models/provider_branches_models/provider_model.dart';
import 'package:mc_common_app/models/provider_branches_models/provider_profile_model.dart';
import 'package:mc_common_app/models/services_models/item_model.dart';

abstract class BranchRepo {
  Future<MResponse> createBranch(String branchName, String branchDescription, String cityId, String address, String latitude, String longitude);

  Future<MResponse> updateBranch(int id, String branchName, String branchDescription, String cityId, String address, String latitude, String longitude, {bool isNeedToDelete = true});

  Future<Branch> fetchAllBranches();

  Future<Category> fetchBranchCategory();

  Future<Services> fetchServicesByCategoryId({required int serviceCategoryId});

  Future<Services> fetchProviderServices(String branchID, String serviceCategoryId);

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

  Future<Document> getServiceProviderDocument(dynamic userId);

  Future<MResponse> serviceProviderDocumentsUpdate(List<DocumentData>? documents);

  Future<ProviderModel> getBranchAndServices();

  Future<List<ProviderBasicDataModel>> getAllProvidersWitheBasicData();

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

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

  Future<MResponse> getMatchedServices(int oldBranchId, int newBranchId, int categoryId);

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

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

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

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

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

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

  Future<List<BranchDetailModel>> getAllNearBranchAndServices();

  Future<List<ItemData>> getServiceItems(int serviceId);

  Future<ProviderProfileModel> getBranchAndServicesByProviderId(int providerId);

  Future<List<BranchDetailModel>> getBranchesByFilters({
    List<int>? providerIdsList,
    List<int>? categoryIdsList,
    List<int>? serviceIdsList,
    int? distanceKm,
    int? rating,
    double? latitude,
    double? longitude,
  });
}

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

  @override
  Future<MResponse> createBranch(String branchName, String branchDescription, String cityId, String address, String latitude, String longitude) async {
    var postParams = {
      "serviceProviderID": AppState().getUser.data?.userInfo?.providerId ?? "",
      "branchName": branchName,
      "branchDescription": branchDescription,
      "cityID": cityId,
      "address": address,
      "latitude": latitude,
      "longitude": longitude,
      "isActive": true
    };
    String t = AppState().getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.createProviderBranch, postParams, token: t);
  }

  @override
  Future<Branch> fetchAllBranches() async {
    var postParams = {"ServiceProviderID": AppState().getUser.data?.userInfo?.providerId.toString() ?? ""};
    String t = AppState().getUser.data!.accessToken ?? "";
    return await apiClient.getJsonForObject((json) => Branch.fromJson(json), ApiConsts.ServiceProviderBranchGet, queryParameters: postParams, token: t);
  }

  @override
  Future<Category> fetchBranchCategory() async {
    var postParams = {"ServiceProviderID": AppState().getUser.data?.userInfo?.providerId.toString() ?? ""};
    String t = AppState().getUser.data!.accessToken ?? "";
    return await apiClient.getJsonForObject((json) => Category.fromJson(json), ApiConsts.ServiceCategory_Get, queryParameters: postParams, token: t);
  }

  @override
  Future<Services> fetchServicesByCategoryId({required int serviceCategoryId}) async {
    var postParams = {"ServiceCategoryID": serviceCategoryId.toString()};
    String t = AppState().getUser.data!.accessToken ?? "";
    return await apiClient.getJsonForObject((json) => Services.fromJson(json), ApiConsts.Services_Get, queryParameters: serviceCategoryId.toString() != "-1" ? postParams : null, token: t);
  }

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

  @override
  Future<Document> getServiceProviderDocument(dynamic userId) async {
    var queryParameters = {
      "ServiceProviderID": userId.toString(),
    };
    String? token = AppState().getUser.data?.accessToken;
    debugPrint(token);
    return await injector
        .get<ApiClient>()
        .getJsonForObject((json) => Document.fromJson(json), ApiConsts.GetProviderDocument, queryParameters: queryParameters, token: AppState().getUser.data!.accessToken ?? "");
  }

  @override
  Future<MResponse> serviceProviderDocumentsUpdate(List<DocumentData>? documents) async {
    List<Map<String, dynamic>> map = [];
    for (int i = 0; i < documents!.length; i++) {
      if (documents[i].document != null) {
        var postParams = {
          "id": documents[i].id,
          "serviceProviderID": documents[i].serviceProviderId,
          "documentID": documents[i].documentId,
          "documentExt": documents[i].fileExt,
          "documentImage": documents[i].document,
          "isActive": true
        };
        map.add(postParams);
      }
    }
    String t = AppState().getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.ServiceProviderDocument_Update, map, token: t);
  }

  @override
  Future<ProviderModel> getBranchAndServices() async {
    var postParams = {"serviceProviderID": AppState().getUser.data?.userInfo?.providerId.toString() ?? ""};
    String t = AppState().getUser.data!.accessToken ?? "";
    return await apiClient.getJsonForObject((json) => ProviderModel.fromJson(json), ApiConsts.BranchesAndServices, queryParameters: postParams, token: t);
  }

  @override
  Future<List<ProviderBasicDataModel>> getAllProvidersWitheBasicData() async {
    String t = AppState().getUser.data!.accessToken ?? "";

    GenericRespModel adsGenericModel = await apiClient.getJsonForObject(
      token: t,
      (json) => GenericRespModel.fromJson(json),
      ApiConsts.serviceProviderDDLGet,
    );
    List<ProviderBasicDataModel> providersList = List.generate(adsGenericModel.data.length, (index) => ProviderBasicDataModel.fromJson(adsGenericModel.data[index]));
    return providersList;
  }

  @override
  Future<MResponse> updateBranch(int id, String branchName, String branchDescription, String cityId, String address, String latitude, String longitude, {bool isNeedToDelete = true}) async {
    String lat = "0", long = "0";
    try {
      lat = latitude.substring(0, 9);
      long = longitude.substring(0, 9);
    } catch (e) {}
    var postParams = {
      "id": id,
      "serviceProviderID": AppState().getUser.data?.userInfo?.providerId ?? "",
      "branchName": branchName,
      "branchDescription": branchDescription,
      "cityID": cityId,
      "address": address,
      "latitude": lat,
      "longitude": long,
      "isActive": isNeedToDelete
    };
    String t = AppState().getUser.data!.accessToken ?? "";
    return await apiClient.postJsonForObject((json) => MResponse.fromJson(json), ApiConsts.updateProviderBranch, postParams, token: t);
  }

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

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

  @override
  Future<MResponse> getMatchedServices(int oldBranchId, int newBranchId, int categoryId) async {
    var postParams = {
      "ProviderBranchIDExisted": oldBranchId.toString(),
      "ProviderBranchIDNew": newBranchId.toString(),
      "CategoryID": categoryId.toString(),
    };
    String t = AppState().getUser.data!.accessToken ?? "";
    return await apiClient.getJsonForObject((json) => MResponse.fromJson(json), ApiConsts.getMatchedServices, queryParameters: postParams, token: t);
  }

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

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

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

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

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

  @override
  Future<Services> fetchProviderServices(String branchID, String serviceCategoryId) async {
    var postParams = {
      "ServiceCategoryID": serviceCategoryId,
      "ProviderBranchID": branchID,
    };
    String t = AppState().getUser.data!.accessToken ?? "";
    debugPrint("token " + t);
    return await apiClient.getJsonForObject((json) => Services.fromJson(json), ApiConsts.GetProviderServices, queryParameters: postParams, token: t);
  }

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

  @override
  Future<List<BranchDetailModel>> getAllNearBranchAndServices() async {
    GenericRespModel adsGenericModel = await apiClient.getJsonForObject((json) => GenericRespModel.fromJson(json), ApiConsts.GetAllNearBranches, token: appState.getUser.data!.accessToken);
    List<BranchDetailModel> nearBranches = List.generate(adsGenericModel.data.length, (index) => BranchDetailModel.fromJson(adsGenericModel.data[index]));
    return nearBranches;
  }

  @override
  Future<List<ItemData>> getServiceItems(int serviceId) async {
    var queryParameters = {
      "ServiceProviderServiceID": serviceId.toString(),
    };

    GenericRespModel adsGenericModel = await apiClient.getJsonForObject(
      (json) => GenericRespModel.fromJson(json),
      ApiConsts.getServiceItems,
      token: appState.getUser.data!.accessToken,
      queryParameters: queryParameters,
    );
    List<ItemData> serviceItems = List.generate(adsGenericModel.data.length, (index) => ItemData.fromJson(adsGenericModel.data[index]));
    return serviceItems;
  }

  @override
  Future<ProviderProfileModel> getBranchAndServicesByProviderId(int providerId) async {
    var postParams = {"serviceProviderID": providerId.toString()};
    GenericRespModel adsGenericModel =
        await apiClient.getJsonForObject((json) => GenericRespModel.fromJson(json), ApiConsts.BranchesAndServices, token: appState.getUser.data!.accessToken, queryParameters: postParams);

    return ProviderProfileModel.fromJson(adsGenericModel.data);
  }

  @override
  Future<List<BranchDetailModel>> getBranchesByFilters({
    List<int>? providerIdsList,
    List<int>? categoryIdsList,
    List<int>? serviceIdsList,
    int? distanceKm,
    int? rating,
    double? latitude,
    double? longitude,
  }) async {
    List<String> providerIds = [];
    if (providerIdsList != null) {
      for (var element in providerIdsList) {
        providerIds.add(element.toString());
      }
    }
    List<String> categoryIds = [];
    if (categoryIdsList != null) {
      for (var element in categoryIdsList) {
        categoryIds.add(element.toString());
      }
    }
    List<String> serviceIds = [];
    if (serviceIdsList != null) {
      for (var element in serviceIdsList) {
        serviceIds.add(element.toString());
      }
    }
    var postParams = {
      "ServiceProviderIDs": providerIds,
      "ServiceCategoryIDs": categoryIds,
      "ServiceIDs": serviceIds,
      "DistanceByKM": "${distanceKm ?? 0}",
      "Rating": "${rating ?? 0}",
      "Latitude": latitude.toString(),
      "Longitude": longitude.toString(),
    };

    GenericRespModel adsGenericModel = await apiClient.getJsonForObject(
      (json) => GenericRespModel.fromJson(json),
      ApiConsts.GetAllNearBranches,
      token: appState.getUser.data!.accessToken,
      queryParameters: postParams,
    );
    List<BranchDetailModel> nearBranches = List.generate(adsGenericModel.data.length, (index) => BranchDetailModel.fromJson(adsGenericModel.data[index]));
    return nearBranches;
  }
}
