import 'package:rasadyar_chicken/data/models/request/steward_allocation/steward_allocation_request.dart';
import 'package:rasadyar_chicken/data/models/response/waiting_arrival/waiting_arrival.dart';
import 'package:rasadyar_chicken/presentation/pages/root/logic.dart';
import 'package:rasadyar_core/core.dart';

class BuyInProvinceAllLogic extends GetxController {
  RxList<int> isExpandedList = <int>[].obs;
  Rxn<Jalali> fromDateFilter = Rxn();
  Rxn<Jalali> toDateFilter = Rxn();
  RxnString searchedValue = RxnString();
  RxMap<String, bool> isLoadingConfirmMap = RxMap();
  final RxBool isLoadingMoreAllocationsMade = false.obs;
  RxInt currentPage = 1.obs;

  RootLogic rootLogic = Get.find<RootLogic>();

  Rx<Resource<PaginationModel<WaitingArrivalModel>>> allProduct =
      Resource<PaginationModel<WaitingArrivalModel>>.loading().obs;

  @override
  void onInit() {
    super.onInit();
    getAllArrivals();
  }

  @override
  void onReady() {
    debounce(searchedValue, (callback) => getAllArrivals(), time: Duration(milliseconds: 2000));
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  Future<void> getAllArrivals([bool isLoadingMore = false]) async {
    if (isLoadingMore) {
      isLoadingMoreAllocationsMade.value = true;
    } else {
      allProduct.value = Resource<PaginationModel<WaitingArrivalModel>>.loading();
    }

    if (searchedValue.value != null &&
        searchedValue.value!.trim().isNotEmpty &&
        currentPage.value > 1) {
      currentPage.value = 1;
    }

    safeCall(
      call: () async => await rootLogic.chickenRepository.getWaitingArrivals(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(
          queryParams: {'type': 'all'},
          pageSize: 20,
          page: currentPage.value,
          search: 'filter',
          role: 'Steward',
          value: searchedValue.value,
          fromDate: fromDateFilter.value?.toDateTime(),
          toDate: toDateFilter.value?.toDateTime(),
        ),
      ),
      onSuccess: (res) async {
        await Future.delayed(Duration(milliseconds: 200));
        if ((res?.count ?? 0) == 0) {
          allProduct.value = Resource<PaginationModel<WaitingArrivalModel>>.empty();
        } else {
          allProduct.value = Resource<PaginationModel<WaitingArrivalModel>>.success(
            PaginationModel<WaitingArrivalModel>(
              count: res?.count ?? 0,
              next: res?.next,
              previous: res?.previous,
              results: [...(allProduct.value.data?.results ?? []), ...(res?.results ?? [])],
            ),
          );
        }
      },
    );
  }

  Future<void> acceptEntries(WaitingArrivalModel model) async {
    var request = StewardAllocationRequest(
      allocationKey: model.key,
      checkAllocation: true,
      state: 'accepted',
      receiverRealNumberOfCarcasses: model.realNumberOfCarcasses ?? 0,
      receiverRealWeightOfCarcasses: model.realWeightOfCarcasses?.toInt() ?? 0,
      registrationCode: model.registrationCode ?? 0,
      weightLossOfCarcasses: model.weightLossOfCarcasses?.toInt() ?? 0,
    ).toJson();
    request.removeWhere((key, value) => value == null);

    safeCall(
      call: () async => await rootLogic.chickenRepository.setSateForArrivals(
        token: rootLogic.tokenService.accessToken.value!,
        request: request,
      ),
      onError: (error, stackTrace) {
        eLog(error);
      },
      onSuccess: (result) {
        getAllArrivals();
        rootLogic.getInventory();
      },
    );
  }

  Future<void> denyEntries(WaitingArrivalModel model) async {
    var request = StewardAllocationRequest(
      allocationKey: model.key,
      checkAllocation: true,
      state: 'rejected',
    ).toJson();
    request.removeWhere((key, value) => value == null);

    safeCall(
      call: () async => await rootLogic.chickenRepository.setSateForArrivals(
        token: rootLogic.tokenService.accessToken.value!,
        request: request,
      ),
      onError: (error, stackTrace) {
        eLog(error);
      },
      onSuccess: (result) {
        getAllArrivals();
        rootLogic.getInventory();
      },
    );
  }

  String getVecPathItem(String? item) {
    switch (item) {
      case 'pending':
        return Assets.vec.timerSvg.path;
      case 'accepted':
        return Assets.vec.checkSquareSvg.path;
      case 'rejected':
        return Assets.vec.closeCircleSvg.path;
      default:
        return Assets.vec.timerSvg.path;
    }
  }
}
