import 'package:flutter/material.dart';
import 'package:rasadyar_auth/data/utils/safe_call.dart';
import 'package:rasadyar_chicken/data/models/request/conform_allocation/conform_allocation.dart';
import 'package:rasadyar_chicken/data/models/request/submit_steward_allocation/submit_steward_allocation.dart';
import 'package:rasadyar_chicken/data/models/response/allocated_made/allocated_made.dart';
import 'package:rasadyar_chicken/data/models/response/guild/guild_model.dart';
import 'package:rasadyar_chicken/data/models/response/guild_profile/guild_profile.dart';
import 'package:rasadyar_chicken/data/models/response/roles_products/roles_products.dart';
import 'package:rasadyar_chicken/presentation/pages/root/logic.dart';
import 'package:rasadyar_core/core.dart';

class SalesInProvinceLogic extends GetxController {
  var rootLogic = Get.find<RootLogic>();
  Rxn<List<AllocatedMadeModel>?> allocatedMadeModel = Rxn<List<AllocatedMadeModel>?>();
  RxList<int> isExpandedList = <int>[].obs;

  RxList<ProductModel> rolesProductsModel = RxList<ProductModel>();
  RxBool searchIsSelected = false.obs;
  RxnString searchedValue = RxnString();
  RxList<GuildModel> guildsModel = <GuildModel>[].obs;

  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  Rxn<Jalali> fromDateFilter = Rxn<Jalali>(null);
  Rxn<Jalali> toDateFilter = Rxn<Jalali>(null);
  Rxn<ProductModel> selectedProductModel = Rxn<ProductModel>();
  Rxn<GuildModel> selectedGuildModel = Rxn<GuildModel>();
  Rxn<GuildProfile> guildProfile = Rxn<GuildProfile>();
  RxInt saleType = 1.obs;
  RxInt weight = 0.obs;
  RxInt pricePerKilo = 0.obs;
  RxInt totalCost = 0.obs;
  RxBool isValid = false.obs;
  final weightController = TextEditingController();
  final pricePerKiloController = TextEditingController();
  final totalCostController = TextEditingController();

  final ScrollController scrollControllerAllocationsMade = ScrollController();
  final RxInt currentPageAllocationsMade = 1.obs;
  final RxBool isLoadingMoreAllocationsMade = false.obs;
  final RxBool addPageAllocationsMade = false.obs;
  final RxBool hasMoreDataAllocationsMade = true.obs;

  Rxn<AllocatedMadeModel> selectedAllocationModelForUpdate = Rxn<AllocatedMadeModel>();
  SubmitStewardAllocation? tmpStewardAllocation;

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

    getAllocatedMade();
    getRolesProducts();
    getGuilds();
    getGuildProfile();
    ever(saleType, (callback) {
      getGuilds();
    });
    debounce(weight, time: Duration(milliseconds: 110), (callback) {
      totalCost.value = callback * weight.value;
    });

    debounce(pricePerKilo, time: Duration(milliseconds: 100), (callback) {
      totalCost.value = callback * weight.value;
    });

    totalCost.listen((data) {
      totalCostController.text = data.toString().separatedByComma;

      isValid.value =
          weight.value > 0 &&
          pricePerKilo.value > 0 &&
          totalCost.value > 0 &&
          selectedProductModel.value != null &&
          selectedGuildModel.value != null;
    });

    scrollControllerAllocationsMade.addListener(() {
      if (scrollControllerAllocationsMade.position.pixels >=
          scrollControllerAllocationsMade.position.maxScrollExtent - 100) {
        addPageAllocationsMade.value = true;
        getAllocatedMade();
      }
    });

    debounce(searchedValue, (callback) => getAllocatedMade(), time: Duration(milliseconds: 2000));
    ever(searchIsSelected, (data) {
      if (data == false) {
        searchedValue.value = null;
      }
    });
  }

  Future<void> getAllocatedMade() async {
    if (isLoadingMoreAllocationsMade.value || !hasMoreDataAllocationsMade.value) {
      return;
    }

    if (searchIsSelected.value) {
      currentPageAllocationsMade.value = 1;
    } else if (addPageAllocationsMade.value) {
      currentPageAllocationsMade.value++;
    }
    safeCall(
      call: () async => await rootLogic.chickenRepository.getAllocatedMade(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(
          page: currentPageAllocationsMade.value,
          pageSize: 20,
          search: 'filter',
          role: 'Steward',
          value: searchedValue.value,
        ),
      ),
      onSuccess: (result) {
        if (result != null) {
          if (isLoadingMoreAllocationsMade.value &&
              allocatedMadeModel.value != null &&
              (allocatedMadeModel.value?.isNotEmpty ?? false)) {
            allocatedMadeModel.value?.addAll(result.results!);
          } else {
            allocatedMadeModel.value = result.results;
          }
        }

        isLoadingMoreAllocationsMade.value = false;
      },
      onError: (error, stacktrace) {
        isLoadingMoreAllocationsMade.value = false;
      },
    );
  }

  void checkVerfication() {
    isValid.value =
        weight.value > 0 &&
        pricePerKilo.value > 0 &&
        totalCost.value > 0 &&
        selectedProductModel.value != null &&
        selectedGuildModel.value != null;
  }

  void confirmAllocation(ConformAllocation allocation) {
    safeCall(
      call: () async => await rootLogic.chickenRepository.confirmAllocation(
        token: rootLogic.tokenService.accessToken.value!,
        allocation: allocation.toJson(),
      ),
      onSuccess: (result) {
        getAllocatedMade();
      },
      onError: (error, stacktrace) {},
    );
  }

  void denyAllocation(String token) {
    safeCall(
      call: () async => await rootLogic.chickenRepository.denyAllocation(
        token: rootLogic.tokenService.accessToken.value!,
        allocationToken: token,
      ),
      onSuccess: (result) {
        getAllocatedMade();
      },
      onError: (error, stacktrace) {},
    );
  }

  Future<void> confirmAllAllocations() async {
    safeCall(
      call: () async => await rootLogic.chickenRepository.confirmAllAllocation(
        token: rootLogic.tokenService.accessToken.value!,
        allocationTokens: allocatedMadeModel.value?.map((e) => e.key!).toList() ?? [],
      ),
      onSuccess: (result) {
        getAllocatedMade();
      },
      onError: (error, stacktrace) {},
    );
  }

  Future<void> getRolesProducts() async {
    safeCall(
      call: () async =>
          await rootLogic.chickenRepository.getRolesProducts(token: rootLogic.tokenService.accessToken.value!),
      onSuccess: (result) {
        if (result != null) {
          rolesProductsModel.value = result;
          selectedProductModel.value = result.first;
        }
      },
      onError: (error, stacktrace) {},
    );
  }

  Future<void> getGuilds() async {
    safeCall(
      call: () async => await rootLogic.chickenRepository.getGuilds(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(queryParams: {'free': saleType.value == 2 ? true : false}, role: 'Steward'),
      ),
      onSuccess: (result) {
        if (result != null) {
          guildsModel.clear();
          guildsModel.addAll(result);
        }
      },
      onError: (error, stacktrace) {},
    );
  }

  Future<void> addSale() async {}

  void setSelectedGuild(GuildModel value) {
    selectedGuildModel.value = value;
    update();
  }

  void setSelectedProduct(ProductModel value) {
    selectedProductModel.value = value;
    update();
  }

  Future<void> getGuildProfile() async {
    await safeCall(
      call: () async => await rootLogic.chickenRepository.getProfile(token: rootLogic.tokenService.accessToken.value!),
      onError: (error, stackTrace) {},
      onSuccess: (result) {
        guildProfile.value = result;
      },
    );
  }

  void setSubmitData() {
    tmpStewardAllocation = SubmitStewardAllocation(
      approvedPriceStatus: false,
      allocationType:
          '${guildProfile.value?.steward == true ? "steward" : "guild"}_${selectedGuildModel.value?.steward == true ? "steward" : "guild"}',
      sellerType: guildProfile.value?.steward == true ? "Steward" : "Guild",
      buyerType: selectedGuildModel.value?.steward == true ? "Steward" : "Guild",
      amount: pricePerKilo.value,
      totalAmount: totalCost.value,
      weightOfCarcasses: weight.value,
      sellType: saleType.value == 2 ? "free" : 'exclusive',
      numberOfCarcasses: 0,
      guildKey: selectedGuildModel.value?.key,
      productKey: selectedProductModel.value?.key,
      date: DateTime.now().formattedDashedGregorian,
      type: "manual",
    );
  }

  Future<void> submitAllocation() async {
    safeCall(
      call: () async => await rootLogic.chickenRepository.postSubmitStewardAllocation(
        token: rootLogic.tokenService.accessToken.value!,
        request: tmpStewardAllocation!,
      ),

      onSuccess: (result) {
        getAllocatedMade();
      },
      onError: (error, stackTrace) {},
    );
  }

  Future<void> deleteAllocation(AllocatedMadeModel model) async {
    safeCall(
      call: () async => await rootLogic.chickenRepository.deleteStewardAllocation(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: {'steward_allocation_key': model.key},
      ),

      onSuccess: (result) {
        getAllocatedMade();
      },
      onError: (error, stackTrace) {},
    );
  }

  @override
  void dispose() {
    rootLogic.inventoryExpandedList.clear();
    super.dispose();
  }

  void setEditData(AllocatedMadeModel item) {
    selectedAllocationModelForUpdate.value = item;
    selectedProductModel.value = rolesProductsModel.first;
    selectedGuildModel.value = GuildModel(guildsName: 'tst');
    weight.value = item.weightOfCarcasses ?? 0;
    pricePerKilo.value = item.amount ?? 0;
    totalCost.value = item.totalAmount ?? 0;
    weightController.text = weight.value.toString().separatedByComma;
    pricePerKiloController.text = pricePerKilo.value.toString().separatedByComma;
    totalCostController.text = totalCost.value.toString().separatedByComma;
    isValid.value = true;
  }

  void clearForm() {
    selectedGuildModel.value = null;
    weight.value = 0;
    pricePerKilo.value = 0;
    totalCost.value = 0;
    weightController.clear();
    pricePerKiloController.clear();
    totalCostController.clear();
    isValid.value = false;
  }

  Future<void> updateAllocation() async {
    ConformAllocation updatedAllocationModel = ConformAllocation(
      allocation_key: selectedAllocationModelForUpdate.value?.key,
      amount: pricePerKilo.value,
      total_amount: totalCost.value,
      number_of_carcasses: 0,
      weight_of_carcasses: weight.value,
    );

    safeCall(
      call: () async => await rootLogic.chickenRepository.updateStewardAllocation(
        token: rootLogic.tokenService.accessToken.value!,
        request: updatedAllocationModel,
      ),

      onSuccess: (result) {
        getAllocatedMade();
      },
      onError: (error, stackTrace) {},
    );
  }
}
