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<AllocatedMadeModel> allocatedMadeModel = Rxn<AllocatedMadeModel>();
  RxList<ProductModel> rolesProductsModel = RxList<ProductModel>();

  RxList<GuildModel> guildsModel = <GuildModel>[].obs;

  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;

  @override
  void onInit() {
    super.onInit();
    //rootLogic.getInventory();
    getAllocatedMade();
    getRolesProducts();
    getGuilds();
    getGuildProfile();
    ever(saleType, (callback) {
      getGuilds();
    });

    weight.listen((num) {
      totalCost.value = num * pricePerKilo.value;
    });

    pricePerKilo.listen((num) {
      totalCost.value = num * weight.value;
    });

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

      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();
      }
    });
  }

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

    if (addPageAllocationsMade.value) {
      currentPageAllocationsMade.value++;
    }
    safeCall(
      call: () async => await rootLogic.chickenRepository.getAllocatedMade(
        token: rootLogic.tokenService.accessToken.value!,
        page: currentPageAllocationsMade.value,
      ),
      onSuccess: (result) {
        if (result != null) {
          if (isLoadingMoreAllocationsMade.value &&
              allocatedMadeModel.value?.results != null) {
            allocatedMadeModel.value?.results?.addAll(result.results!);
          } else {
            allocatedMadeModel.value = result;
          }
        }

        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?.results?.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;
        }
      },
      onError: (error, stacktrace) {},
    );
  }

  Future<void> getGuilds() async {
    safeCall(
      call: () async => await rootLogic.chickenRepository.getGuilds(
        token: rootLogic.tokenService.accessToken.value!,
        isFree: saleType.value == 2 ? true : false,
      ),
      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;
      },
    );
  }

  Future<void> submitAllocation() async {
    SubmitStewardAllocation stewardAllocation = 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,
      guildKey: selectedGuildModel.value?.key,
      productKey: selectedProductModel.value?.key,
      date: DateTime.now().formattedGregorianDate,
      type: "manual",
    );

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

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



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