import 'package:rasadyar_chicken/presentation/pages/steward/buy/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/buy_in_province_all/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/buy_in_province_waiting/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/root/logic.dart';
import 'package:rasadyar_core/core.dart';

class BuyInProvinceLogic extends GetxController {
  RxList<String> routesName = RxList();
  RxList<int> isExpandedList = <int>[].obs;
  RxnString searchedValue = RxnString();
  Rx<Jalali> fromDateFilter = Jalali.now().obs;
  Rx<Jalali> toDateFilter = Jalali.now().obs;

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

  BuyLogic get buyLogic => Get.find<BuyLogic>();
  RxInt selectedSegmentIndex = 0.obs;

  BuyInProvinceAllLogic buyAllLogic = Get.find<BuyInProvinceAllLogic>();
  BuyInProvinceWaitingLogic buyWaitingLogic = Get.find<BuyInProvinceWaitingLogic>();

  @override
  void onInit() {
    super.onInit();
    routesName.value = [...buyLogic.routesName, 'داخل استان'].toList();
    routesName.add(selectedSegmentIndex.value == 0 ? 'در انتظار' : 'کل خریدها');
    ever(selectedSegmentIndex, (callback) {
      routesName.removeLast();
      routesName.add(callback == 0 ? 'در انتظار' : 'کل خریدها');
    });

    ever(fromDateFilter, (callback) => _setFromDateFilter(callback));
    ever(toDateFilter, (callback) => _setToDateFilter(callback));
  }

  @override
  void onReady() {
    fLog('BuyInProvinceLogic onReady');
    super.onReady();
  }

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

  void _setFromDateFilter(Jalali jalali) {
    final isWaiting = selectedSegmentIndex.value == 0;
    if (isWaiting) {
      buyWaitingLogic.fromDateFilter.value = fromDateFilter.value;
    } else {
      buyAllLogic.fromDateFilter.value = fromDateFilter.value;
    }
  }

  void _setToDateFilter(Jalali jalali) {
    final isWaiting = selectedSegmentIndex.value == 0;
    if (isWaiting) {
      buyWaitingLogic.toDateFilter.value = fromDateFilter.value;
    } else {
      buyAllLogic.toDateFilter.value = fromDateFilter.value;
    }
  }

  Future<void> submitFilter() async {
    final isWaiting = selectedSegmentIndex.value == 0;
    if (isWaiting) {
      buyWaitingLogic.getWaitingArrivals();
    } else {
      buyAllLogic.getAllArrivals();
    }
  }

  void setSearchValue(String? data) {
    searchedValue.value = data?.trim();
    final isWaiting = selectedSegmentIndex.value == 0;
    if (isWaiting) {
      buyWaitingLogic.searchedValue.value = searchedValue.value;
    } else {
      buyAllLogic.searchedValue.value = searchedValue.value;
    }
  }

  Future<void> onRefresh() async {
    final isWaiting = selectedSegmentIndex.value == 0;
    await rootLogic.onRefresh();
    await Future.wait([buyWaitingLogic.getWaitingArrivals(), buyAllLogic.getAllArrivals()]);
  }
}
