import 'package:flutter/material.dart';

import 'package:rasadyar_chicken/data/models/response/iran_province_city/iran_province_city_model.dart';
import 'package:rasadyar_chicken/data/models/response/out_province_carcasses_buyer/out_province_carcasses_buyer.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/root/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/sale/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/sales_out_of_province/logic.dart';
import 'package:rasadyar_chicken/presentation/utils/utils.dart';
import 'package:rasadyar_core/core.dart';

class SalesOutOfProvinceBuyersLogic extends GetxController {
  StewardRootLogic  rootLogic = Get.find<StewardRootLogic>();

  SaleLogic get saleLogic => Get.find<SaleLogic>();

  SalesOutOfProvinceLogic get saleOutOfProvince => Get.find<SalesOutOfProvinceLogic>();

  RxInt currentPage = 1.obs;
  RxInt expandedListIndex = (-1).obs;
  Rx<Jalali> fromDateFilter = Jalali.now().obs;
  Rx<Jalali> toDateFilter = Jalali.now().obs;
  RxnString searchedValue = RxnString();

  RxBool isLoadingMoreAllocationsMade = false.obs;
  RxBool isBuyerSubmitButtonEnabled = false.obs;

  RxList<IranProvinceCityModel> cites = <IranProvinceCityModel>[].obs;
  Rxn<IranProvinceCityModel> selectedProvince = Rxn();
  Rxn<IranProvinceCityModel> selectedCity = Rxn();

  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  TextEditingController buyerNameController = TextEditingController();
  TextEditingController buyerLastNameController = TextEditingController();
  TextEditingController buyerPhoneController = TextEditingController();
  TextEditingController buyerUnitNameController = TextEditingController();
  String? key;

  Rx<Resource<PaginationModel<OutProvinceCarcassesBuyer>>> buyerList =
      Resource<PaginationModel<OutProvinceCarcassesBuyer>>.loading().obs;

  RxList<String> routesName = RxList();

  @override
  void onInit() {
    super.onInit();
    routesName.value = [...saleLogic.routesName, 'خریداران'].toList();
    getOutProvinceCarcassesBuyer();
  }

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

    selectedProvince.listen((p0) => getCites());

    debounce(
      searchedValue,
      (callback) => getOutProvinceCarcassesBuyer(),
      time: Duration(milliseconds: timeDebounce),
    );

    setupListeners();
  }

  @override
  void onClose() {
    buyerNameController.dispose();
    buyerLastNameController.dispose();
    buyerPhoneController.dispose();
    buyerUnitNameController.dispose();
    selectedCity.value = null;
    selectedProvince.value = null;

    super.onClose();
  }

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

    if (searchedValue.value != null &&
        searchedValue.value!.trim().isNotEmpty &&
        currentPage.value > 1) {
      currentPage.value = 1; // Reset to first page if search value is set
    }

    await safeCall(
      call: () => rootLogic.chickenRepository.getOutProvinceCarcassesBuyer(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(
          pageSize: 20,
          page: currentPage.value,
          state: 'buyer-list',
          search: 'filter',
          role: 'Steward',
          value: searchedValue.value ?? '',
        ),
      ),
      onError: (error, stackTrace) => isLoadingMoreAllocationsMade.value = false,
      onSuccess: (res) {
        if ((res?.count ?? 0) == 0) {
          buyerList.value = Resource<PaginationModel<OutProvinceCarcassesBuyer>>.empty();
        } else {
          buyerList.value = Resource<PaginationModel<OutProvinceCarcassesBuyer>>.success(
            PaginationModel<OutProvinceCarcassesBuyer>(
              count: res?.count ?? 0,
              next: res?.next,
              previous: res?.previous,
              results: [...(buyerList.value.data?.results ?? []), ...(res?.results ?? [])],
            ),
          );

          isLoadingMoreAllocationsMade.value = false;
        }
      },
    );
  }

  void resetSubmitForm() {
    buyerNameController.clear();
    buyerLastNameController.clear();
    buyerPhoneController.clear();
    buyerUnitNameController.clear();
    selectedProvince.value = null;
    selectedCity.value = null;
  }

  Future<void> getCites() async {
    await safeCall(
      call: () =>
          rootLogic.chickenRepository.getCity(provinceName: selectedProvince.value?.name ?? ''),
      onSuccess: (result) {
        if (result != null && result.isNotEmpty) {
          cites.value = result;
        }
      },
    );
  }

  void setupListeners() {
    buyerNameController.addListener(checkBuyerFormValid);
    buyerLastNameController.addListener(checkBuyerFormValid);
    buyerPhoneController.addListener(checkBuyerFormValid);
    buyerUnitNameController.addListener(checkBuyerFormValid);
    ever(selectedProvince, (_) => checkBuyerFormValid());
    ever(selectedCity, (_) => checkBuyerFormValid());
  }

  void checkBuyerFormValid() {
    isBuyerSubmitButtonEnabled.value =
        buyerNameController.text.isNotEmpty &&
        buyerLastNameController.text.isNotEmpty &&
        buyerPhoneController.text.isNotEmpty &&
        buyerUnitNameController.text.isNotEmpty &&
        selectedProvince.value != null &&
        selectedCity.value != null;
  }

  Future<bool> createBuyer() async {
    bool res = false;
    if (!(formKey.currentState?.validate() ?? false)) {
      return res;
    }
    await safeCall(
      call: () async {
        OutProvinceCarcassesBuyer buyer = OutProvinceCarcassesBuyer(
          province: selectedProvince.value!.name,
          city: selectedCity.value!.name,
          firstName: buyerNameController.text,
          lastName: buyerLastNameController.text,
          unitName: buyerUnitNameController.text,
          mobile: buyerPhoneController.text,
          role: 'Steward',
        );
        final res = await rootLogic.chickenRepository.createOutProvinceCarcassesBuyer(
          token: rootLogic.tokenService.accessToken.value!,
          body: buyer,
        );
      },
      onSuccess: (result) {
        getOutProvinceCarcassesBuyer();
        resetSubmitForm();
        res = true;
      },
    );
    return res;
  }

  void setEditDataBuyer(OutProvinceCarcassesBuyer item) {
    buyerNameController.text = item.firstName ?? '';
    buyerLastNameController.text = item.lastName ?? '';
    buyerUnitNameController.text = item.unitName ?? '';
    buyerPhoneController.text = item.mobile ?? '';
    selectedProvince.value = IranProvinceCityModel(name: item.province);
    selectedCity.value = IranProvinceCityModel(name: item.city);
    isBuyerSubmitButtonEnabled.value = true;
  }

  void setSearchValue(String? value) {
    searchedValue.value = value?.trim();
  }

  void submitFilter() {
    fromDateFilter.value = fromDateFilter.value;
    toDateFilter.value = toDateFilter.value;
    getOutProvinceCarcassesBuyer();
  }


  Future<void> onRefresh() async {
    currentPage.value = 1;
    await rootLogic.onRefresh();
    await getOutProvinceCarcassesBuyer();
  }
  void toggleExpansion({int? index}) {
    if (expandedListIndex.value == index || index == null) {
      expandedListIndex.value = -1;
    } else {
      expandedListIndex.value = index;
    }
  }
}
