import 'package:rasadyar_chicken/data/models/response/hatching/hatching_models.dart';
import 'package:rasadyar_chicken/presentation/pages/poultry_science/root/logic.dart';
import 'package:rasadyar_core/core.dart';

class ActiveHatchingLogic extends GetxController {
  PoultryScienceRootLogic rootLogic = Get.find<PoultryScienceRootLogic>();
  BaseLogic baseLogic = Get.find<BaseLogic>();
  Rx<Resource<PaginationModel<HatchingModel>>> activeHatchingList =
      Resource<PaginationModel<HatchingModel>>.loading().obs;

  final RxBool isLoadingMoreList = false.obs;
  RxInt currentPage = 1.obs;
  RxInt expandedIndex = RxInt(-1);
  List<String> routesName = ['اقدام', 'جوجه ریزی فعال'];

  Rx<Jalali> fromDateFilter = Jalali.now().obs;
  Rx<Jalali> toDateFilter = Jalali.now().obs;
  RxnString searchedValue = RxnString();

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

  @override
  void onClose() {
    super.onClose();
    baseLogic.clearSearch();
  }


  Future<void> getHatchingList([bool isLoadingMore = false]) async {
    if (isLoadingMore) {
      isLoadingMoreList.value = true;
    } else {
      activeHatchingList.value = Resource<PaginationModel<HatchingModel>>.loading();
    }

    if (searchedValue.value != null &&
        searchedValue.value!.trim().isNotEmpty &&
        currentPage.value > 1) {
      currentPage.value = 1;
    }

    safeCall(
      call: () async => await rootLogic.poultryRepository.getHatchingPoultry(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(
          queryParams: {'type': 'hatching'},
          role: 'PoultryScience',
          pageSize: 50,
          page: currentPage.value,
        ),
      ),
      onSuccess: (res) {
        if ((res?.count ?? 0) == 0) {
          activeHatchingList.value = Resource<PaginationModel<HatchingModel>>.empty();
        } else {
          activeHatchingList.value = Resource<PaginationModel<HatchingModel>>.success(
            PaginationModel<HatchingModel>(
              count: res?.count ?? 0,
              next: res?.next,
              previous: res?.previous,
              results: [...(activeHatchingList.value.data?.results ?? []), ...(res?.results ?? [])],
            ),
          );
        }
      },
    );
  }

  void toggleExpanded(int index) {
    expandedIndex.value = expandedIndex.value == index ? -1 : index;
  }

  Future<void> onRefresh() async {
    currentPage.value = 1;
    await getHatchingList();
  }


}
