import 'package:flutter/cupertino.dart';
import 'package:rasadyar_auth/data/utils/safe_call.dart';
import 'package:rasadyar_chicken/data/models/request/create_steward_free_bar/create_steward_free_bar.dart';
import 'package:rasadyar_chicken/data/models/response/iran_province_city/iran_province_city_model.dart';
import 'package:rasadyar_chicken/data/models/response/roles_products/roles_products.dart';
import 'package:rasadyar_chicken/data/models/response/steward_free_bar/steward_free_bar.dart';
import 'package:rasadyar_chicken/presentation/pages/out_of_province/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/root/logic.dart';
import 'package:rasadyar_core/core.dart';

class BuysOutOfProvinceLogic extends GetxController {
  RxBool isExpanded = false.obs;
  RxBool isSubmitButtonEnabled = false.obs;
  RxList<int> isExpandedList = <int>[].obs;
  RxBool searchIsSelected = false.obs;

  //TODO add this to Di
  ImagePicker imagePicker = ImagePicker();

  Rx<Resource<List<StewardFreeBar>>> purchaseOutOfProvinceList = Resource<List<StewardFreeBar>>.loading().obs;
  Rxn<ProductModel> selectedProduct = Rxn();

  RxList<IranProvinceCityModel> cites = <IranProvinceCityModel>[].obs;
  Rxn<IranProvinceCityModel> selectedProvince = Rxn();
  Rxn<IranProvinceCityModel> selectedCity = Rxn();
  Rxn<XFile> selectedImage = Rxn<XFile>();
  RxnString _base64Image = RxnString();
  RxnString editImageUrl = RxnString();

  RootLogic get rootLogic => Get.find<RootLogic>();

  OutOfProvinceLogic get outOfTheProvinceLogic => Get.find<OutOfProvinceLogic>();

  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  TextEditingController sellerNameController = TextEditingController();
  TextEditingController sellerPhoneController = TextEditingController();
  TextEditingController carcassWeightController = TextEditingController();

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

  @override
  void onReady() {
    super.onReady();
    getStewardPurchaseOutOfProvince();
    selectedProvince.listen((p0) => getCites());
    tLog(selectedProduct.value);
    outOfTheProvinceLogic.rolesProductsModel.listen((lists) {
      selectedProduct.value = lists.first;
    },);
    tLog(selectedProduct.value);
    setupListeners();
    debounce(searchedValue, (callback) => getStewardPurchaseOutOfProvince(), time: Duration(milliseconds: 2000));
    ever(searchIsSelected, (data) {
      if (data == false) {
        searchedValue.value = null;
      }
    });
  }

  @override
  void onClose() {
    sellerNameController.dispose();
    sellerPhoneController.dispose();
    carcassWeightController.dispose();
    isExpandedList.clear();

    super.onClose();
  }

  Future<void> getStewardPurchaseOutOfProvince() async {
    await safeCall(
      call: () => rootLogic.chickenRepository.getStewardPurchasesOutSideOfTheProvince(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(
          pageSize: 10,
          page: 1,
          search: 'filter',
          role: 'Steward',
          value: searchedValue.value,
          fromDate: fromDateFilter.value.toDateTime(),
          toDate: toDateFilter.value.toDateTime(),
        ),
      ),
      onSuccess: (res) {
        if ((res?.count ?? 0) == 0) {
          purchaseOutOfProvinceList.value = Resource<List<StewardFreeBar>>.empty();
        } else {
          purchaseOutOfProvinceList.value = Resource<List<StewardFreeBar>>.success(res!.results!);
        }
      },
    );
  }

  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() {
    sellerNameController.addListener(checkFormValid);
    sellerPhoneController.addListener(checkFormValid);
    carcassWeightController.addListener(checkFormValid);

    ever(selectedProvince, (_) => checkFormValid());
    ever(selectedCity, (_) => checkFormValid());
    ever(selectedProduct, (_) => checkFormValid());
    ever(selectedImage, (data) async {
      checkFormValid();
      if (data?.path != null) {
        _base64Image.value = await convertImageToBase64(data!.path);
      }
    });
  }

  void checkFormValid() {
    isSubmitButtonEnabled.value =
        sellerNameController.text.isNotEmpty &&
            sellerPhoneController.text.isNotEmpty &&
            carcassWeightController.text.isNotEmpty &&
            selectedProvince.value != null &&
            selectedCity.value != null &&
            selectedProduct.value != null &&
            selectedImage.value != null;
  }

  Future<bool> createStewardPurchaseOutOfProvince() async {
    bool res = false;
    if (!(formKey.currentState?.validate() ?? false)) {
      return res;
    }
    await safeCall(
      call: () async {
        CreateStewardFreeBar createStewardFreeBar = CreateStewardFreeBar(
          productKey: selectedProduct.value!.key,
          killHouseName: sellerNameController.text,
          killHouseMobile: sellerPhoneController.text,
          province: selectedProvince.value!.name,
          city: selectedCity.value!.name,
          weightOfCarcasses: int.parse(carcassWeightController.text.clearComma),
          barImage: _base64Image.value,
          date: DateTime.now().formattedYHMS,
        );
        final res = await rootLogic.chickenRepository.createStewardPurchasesOutSideOfTheProvince(
          token: rootLogic.tokenService.accessToken.value!,
          body: createStewardFreeBar,
        );
      },
      onSuccess: (result) {
        getStewardPurchaseOutOfProvince();
        resetSubmitForm();
        res = true;
      },
    );
    return res;
  }

  void resetSubmitForm() {
    sellerNameController.clear();
    sellerPhoneController.clear();
    carcassWeightController.clear();
    selectedProvince.value = null;
    selectedCity.value = null;
    selectedProduct.value = null;
    selectedImage.value = null;
    _base64Image.value = null;
    editImageUrl.value = null;

    isSubmitButtonEnabled.value = false;
  }

  void setEditData(StewardFreeBar item) {
    editImageUrl.value = item.barImage;
    sellerNameController.text = item.killHouseName ?? '';
    sellerPhoneController.text = item.killHouseMobile ?? '';
    carcassWeightController.text = item.weightOfCarcasses?.toInt().toString() ?? '';
    selectedProvince.value = IranProvinceCityModel(name: item.province);
    selectedCity.value = IranProvinceCityModel(name: item.city);
    selectedProduct.value = outOfTheProvinceLogic.rolesProductsModel.firstWhere(
          (element) => element.key == item.product!.key,
    );
    isSubmitButtonEnabled.value = true;
  }

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