import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rasadyar_chicken/data/models/response/guild/guild_model.dart';
import 'package:rasadyar_chicken/data/models/response/roles_products/roles_products.dart';
import 'package:rasadyar_chicken/data/models/response/segmentation_model/segmentation_model.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/root/logic.dart';
import 'package:rasadyar_chicken/presentation/utils/utils.dart';
import 'package:rasadyar_core/core.dart';

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

  RxBool isLoadingMoreAllocationsMade = false.obs;
  RxInt currentPage = 1.obs;

  late List<String> routesName;
  RxInt selectedSegmentIndex = 0.obs;
  RxBool isExpanded = false.obs;

  RxInt expandedListIndex = (-1).obs;
  Rx<Jalali> fromDateFilter = Jalali.now().obs;
  Rx<Jalali> toDateFilter = Jalali.now().obs;
  RxnString searchedValue = RxnString();
  RxInt segmentType = 1.obs;
  RxInt saleType = 1.obs;
  RxInt quotaType = 1.obs;
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  TextEditingController weightController = TextEditingController(text: '0');
  RxBool isSubmitButtonEnabled = false.obs;
  Rxn<GuildModel> selectedGuildModel = Rxn<GuildModel>();
  Rxn<ProductModel> selectedProduct = Rxn<ProductModel>();
  Rxn<SegmentationModel> selectedSegment = Rxn<SegmentationModel>();

  Rx<Resource<PaginationModel<SegmentationModel>>> segmentationList =
      Resource<PaginationModel<SegmentationModel>>.loading().obs;

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

  @override
  void onInit() {
    super.onInit();
    routesName = ['قطعه‌بندی'].toList();
    once(rootLogic.rolesProductsModel, (callback) => selectedProduct.value = callback.first);
    getAllSegmentation();
    getGuilds();
  }

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

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

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

  void setUpListener() {
    debounce(
      searchedValue,
      (callback) => getAllSegmentation(),
      time: Duration(milliseconds: timeDebounce),
    );
    ever(selectedSegment, (_) {
      validateForm();
    });

    weightController.addListener(() => validateForm());
  }

  void setEditData(SegmentationModel item) {
    selectedSegment.value = item;
    weightController.text = item.weight.toString();
  }

  void clearForm() {
    weightController.text = '0';
    selectedSegment.value = null;
    selectedGuildModel.value = null;
    segmentType.value = 1;
    saleType.value = 1;
    quotaType.value = 1;
  }

  void validateForm() {
    var weight = int.tryParse(weightController.text.trim().clearComma);
    isSubmitButtonEnabled.value =
        selectedProduct.value != null &&
        weightController.text.isNotEmpty &&
        weight! > 0 &&
        (segmentType.value == 1 || (segmentType.value == 2 && selectedGuildModel.value != null));
  }

  Future<void> getAllSegmentation([bool isLoadingMore = false]) async {
    if (isLoadingMore) {
      isLoadingMoreAllocationsMade.value = true;
    } else {
      segmentationList.value = Resource<PaginationModel<SegmentationModel>>.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: () async => await rootLogic.chickenRepository.getSegmentation(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(
          pageSize: 20,
          page: currentPage.value,
          search: 'filter',
          role: 'Steward',
          value: searchedValue.value,
          fromDate: fromDateFilter.value.toDateTime(),
          toDate: toDateFilter.value.toDateTime(),
        ),
      ),

      onSuccess: (result) {
        if ((result?.count ?? 0) == 0) {
          segmentationList.value = Resource<PaginationModel<SegmentationModel>>.empty();
        } else {
          segmentationList.value = Resource<PaginationModel<SegmentationModel>>.success(
            PaginationModel<SegmentationModel>(
              count: result?.count ?? 0,
              next: result?.next,
              previous: result?.previous,
              results: [
                ...(segmentationList.value.data?.results ?? []),
                ...(result?.results ?? []),
              ],
            ),
          );

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

  Future<void> deleteSegmentation(String key) async {
    await safeCall(
      showError: false,
      call: () => rootLogic.chickenRepository.deleteSegmentation(
        token: rootLogic.tokenService.accessToken.value!,
        key: key,
      ),
    );
  }

  Future<bool> editSegment() async {
    var res = true;
    safeCall(
      showError: true,
      call: () async => await rootLogic.chickenRepository.editSegmentation(
        token: rootLogic.tokenService.accessToken.value!,
        model: SegmentationModel(
          key: selectedSegment.value?.key,
          weight: int.tryParse(weightController.text.clearComma) ?? 0,
        ),
      ),
      onSuccess: (result) {
        res = true;
        onRefresh();
      },
      onError: (error, stacktrace) {
        res = false;
      },
    );
    return res;
  }

  Future<bool> createSegment() async {
    var res = true;
    SegmentationModel segmentationModel = SegmentationModel(
      productKey: selectedProduct.value?.key,
      weight: int.tryParse(weightController.text.clearComma) ?? 0,
      saleType: saleType.value == 1 ? 'governmental' : 'free',
      quota: quotaType.value == 1 ? 'governmental' : 'free',
    );
    if (segmentType.value == 2) {
      segmentationModel = segmentationModel.copyWith(guildKey: selectedGuildModel.value?.key);
    }
    await safeCall(
      call: () async => await rootLogic.chickenRepository.createSegmentation(
        token: rootLogic.tokenService.accessToken.value!,
        model: segmentationModel,
      ),
      onSuccess: (result) {
        res = true;
        isSubmitButtonEnabled.value = true;
        onRefresh();
      },
      onError: (error, stacktrace) {
        res = false;
      },
    );
    return res;
  }

  Future<void> getGuilds() async {
    safeCall(
      call: () async => await rootLogic.chickenRepository.getGuilds(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(queryParams: {'all': true}, role: 'Steward'),
      ),
      onSuccess: (result) {
        if (result != null) {
          guildsModel.clear();
          guildsModel.addAll(result);
        }
      },
      onError: (error, stacktrace) {},
    );
  }

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

  void toggleExpansion({int? index}) {
    if (expandedListIndex.value == index || index == null) {
      expandedListIndex.value = -1;
    } else {
      expandedListIndex.value = index;
    }
  }
}
