import 'package:flutter/material.dart';
import 'package:rasadyar_chicken/data/models/response/poultry_farm/poultry_farm.dart';
import 'package:rasadyar_chicken/presentation/pages/poultry_science/home/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/poultry_science/root/logic.dart';
import 'package:rasadyar_core/core.dart';

class FarmLogic extends GetxController {
  List<String> routes = ['اقدام', 'فارم ها'];
  PoultryScienceRootLogic rootLogic = Get.find<PoultryScienceRootLogic>();
  BasePageLogic baseLogic = Get.find<BasePageLogic>();
  final PoultryScienceHomeLogic _homeLogic = Get.find<PoultryScienceHomeLogic>();
  RxList<InformationTagData> tagInfo = <InformationTagData>[
    InformationTagData(
      labelTitle: 'کل فارم ها',
      isLoading: true,
      labelVecIcon: Assets.vec.cubeScanSvg.path,
      iconColor: AppColor.blueNormalOld,
      valueBgColor: Colors.white,
      labelGradient: LinearGradient(
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
        colors: [AppColor.blueLight, Colors.white],
      ),
    ),
    InformationTagData(
      labelTitle: 'حجم جوجه ریزی',
      unit: 'قطعه',
      isLoading: true,
      labelVecIcon: Assets.vec.cubeCardSvg.path,
      blendMode: BlendMode.dst,
      valueBgColor: Colors.white,
      labelGradient: LinearGradient(
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
        colors: [AppColor.greenLightHover, Colors.white],
      ),
    ),
  ].obs;
  Rx<Resource<PaginationModel<PoultryFarm>>> farmList =
      Resource<PaginationModel<PoultryFarm>>.loading().obs;

  RxInt currentPage = 1.obs;
  final RxBool isLoadingMoreList = false.obs;
  RxInt expandedIndex = RxInt(-1);

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

  @override
  void onReady() {
    super.onReady();
    tagInfo[0] = tagInfo[0].copyWith(
      isLoading: false,
      value: _homeLogic.tagInfo['first']!.first.value,
    );
    tagInfo[1] = tagInfo[1].copyWith(
      isLoading: false,
      value: _homeLogic.tagInfo['second']!.first.value,
    );

    getFarmList();
  }

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

  Future<void> getFarmList([bool isLoadingMore = false]) async {
    if (isLoadingMore) {
      isLoadingMoreList.value = true;
    } else {
      farmList.value = Resource<PaginationModel<PoultryFarm>>.loading();
    }
    await safeCall(
      call: () async => await rootLogic.poultryRepository.getPoultryScienceFarmList(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(
          queryParams: {'type': 'farm'},
          role: 'PoultryScience',
          pageSize: 50,
          search: 'filter',
          value: '',
          page: currentPage.value,
        ),
      ),
      onSuccess: (res) {
        if ((res?.count ?? 0) == 0) {
          farmList.value = Resource<PaginationModel<PoultryFarm>>.empty();
        } else {
          farmList.value = Resource<PaginationModel<PoultryFarm>>.success(
            PaginationModel<PoultryFarm>(
              count: res?.count ?? 0,
              next: res?.next,
              previous: res?.previous,
              results: [...(farmList.value.data?.results ?? []), ...?res?.results],
            ),
          );
        }
      },
      onError: (error, stackTrace) {},
    );
  }

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

  Future<void> onRefresh() async {
    currentPage.value = 1;
    farmList.value = Resource<PaginationModel<PoultryFarm>>.loading();
    await getFarmList();
  }
}
