import 'package:flutter/material.dart';
import 'package:rasadyar_auth/data/utils/safe_call.dart';
import 'package:rasadyar_chicken/chicken.dart';
import 'package:rasadyar_chicken/data/models/request/steward_allocation/steward_allocation_request.dart';
import 'package:rasadyar_chicken/data/models/response/bar_information/bar_information.dart';
import 'package:rasadyar_chicken/data/models/response/imported_loads_model/imported_loads_model.dart';
import 'package:rasadyar_chicken/data/models/response/waiting_arrival/waiting_arrival.dart';
import 'package:rasadyar_core/core.dart';

class EnteringTheWarehouseLogic extends GetxController {
  RootLogic rootLogic = Get.find<RootLogic>();
  Rxn<BarInformation> barInformation = Rxn<BarInformation>();
  Rxn<WaitingArrivalModel> waitingForArrival = Rxn<WaitingArrivalModel>();
  Rxn<ImportedLoadsModel> importedLoads = Rxn<ImportedLoadsModel>();
  RxInt acceptType = 1.obs;
  TextEditingController weightController = TextEditingController();
  TextEditingController volumeController = TextEditingController();
  TextEditingController weightLossController = TextEditingController();
  TextEditingController authenticationCodeController = TextEditingController();

  final ScrollController scrollControllerImportedLoad = ScrollController();
  final RxInt currentPageImportedLoad = 1.obs;
  final RxBool isLoadingMoreImportedLoad = false.obs;
  final RxBool addPageImportedLoad = false.obs;
  final RxBool hasMoreDataImportedLoad = true.obs;

  final ScrollController scrollControllerWaitingForArrival = ScrollController();
  final RxInt currentPageWaitingForArrival = 1.obs;
  final RxBool isLoadingMoreWaitingForArrival = false.obs;
  final RxBool addPageWaitingForArrival = false.obs;
  final RxBool hasMoreDataWaitingForArrival = true.obs;

  @override
  void onReady() {
    super.onReady();
    //rootLogic.getInventory();
    getBarGeneralInformation();
    getWaitingArrivals();
    getImportedEntried();

    scrollControllerImportedLoad.addListener(() {
      if (scrollControllerImportedLoad.position.pixels >=
          scrollControllerImportedLoad.position.maxScrollExtent - 100) {
        addPageImportedLoad.value = true;
        getImportedEntried();
      }
    });

    scrollControllerWaitingForArrival.addListener(() {
      if (scrollControllerWaitingForArrival.position.pixels >=
          scrollControllerWaitingForArrival.position.maxScrollExtent - 100) {
        addPageWaitingForArrival.value = true;
        getWaitingArrivals();
      }
    });
  }

  Future<void> getBarGeneralInformation() async {
    safeCall(
      call: () async =>
          await rootLogic.chickenRepository.getGeneralBarInformation(
            token: rootLogic.tokenService.accessToken.value!,
          ),
      onError: (error, stackTrace) {
        eLog(error);
      },
      onSuccess: (result) {
        if (result != null) {
          barInformation.value = result;
        }
      },
    );
  }

  Future<void> getWaitingArrivals() async {
    if (isLoadingMoreWaitingForArrival.value ||
        !hasMoreDataWaitingForArrival.value) {
      return;
    }

    if (addPageWaitingForArrival.value) {
      currentPageWaitingForArrival.value++;
    }

    safeCall(
      call: () async => await rootLogic.chickenRepository.getWaitingArrivals(
        token: rootLogic.tokenService.accessToken.value!,
        page: currentPageWaitingForArrival.value,
      ),
      onError: (error, stackTrace) {
        isLoadingMoreImportedLoad.value = false;
      },
      onSuccess: (result) {
        if (result != null) {
          waitingForArrival.value = result;
          if (isLoadingMoreWaitingForArrival.value) {
            waitingForArrival.value?.results.addAll(result.results);
          } else {
            waitingForArrival.value = result;
          }
        }

        isLoadingMoreImportedLoad.value = false;
      },
    );
  }

  Future<void> acceptEntried(String key) async {
    var request = StewardAllocationRequest(
      allocationKey: key,
      checkAllocation: true,
      state: 'accepted',
      receiverRealNumberOfCarcasses: int.parse(
        volumeController.text.isNotEmpty ? volumeController.text : '0',
      ),
      receiverRealWeightOfCarcasses: int.parse(
        weightController.text.isNotEmpty ? weightController.text : '0',
      ),
      registrationCode: acceptType.value == 1
          ? int.parse(
              authenticationCodeController.text.isNotEmpty
                  ? authenticationCodeController.text
                  : '0',
            )
          : null,
      weightLossOfCarcasses: int.parse(
        weightLossController.text.isNotEmpty ? weightLossController.text : '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) {
        clearControllers();
        getWaitingArrivals();
        getBarGeneralInformation();
      },
    );
  }

  Future<void> denyEntried(String key) async {
    var request = StewardAllocationRequest(
      allocationKey: 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) {
        getWaitingArrivals();
        getBarGeneralInformation();
      },
    );
  }

  Future<void> getImportedEntried() async {
    if (isLoadingMoreImportedLoad.value || !hasMoreDataImportedLoad.value) {
      return;
    }

    if (addPageImportedLoad.value) {
      currentPageImportedLoad.value++;
    }

    safeCall(
      call: () async => await rootLogic.chickenRepository.getImportedLoadsModel(
        token: rootLogic.tokenService.accessToken.value!,
        page: currentPageImportedLoad.value,
      ),
      onError: (error, stackTrace) {
        isLoadingMoreImportedLoad.value = false;
      },
      onSuccess: (result) {
        if (result != null) {
          if (isLoadingMoreImportedLoad.value && result.results != null) {
            importedLoads.value?.results?.addAll(result.results!);
          } else {
            importedLoads.value = result;
          }
          isLoadingMoreImportedLoad.value = false;
        }
      },
    );
  }

  clearControllers() {
    weightController.clear();
    volumeController.clear();
    weightLossController.clear();
    authenticationCodeController.clear();
  }
  @override
  void dispose() {
    rootLogic.inventoryExpandedList.clear();
    super.dispose();
  }

}
