"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_hook_form_1 = require("react-hook-form");
const constants_1 = require("../constants");
const useLogic = ({ control, name, label, options, allLabel = constants_1.FORM_QUICK_FILTERS_DEFAULT_ALL_LABEL, allCounter, multiple = false, maxCount, placeholder, }) => {
    const { field } = (0, react_hook_form_1.useController)({ control, name });
    const filterOptions = options.filter((option) => option.value !== constants_1.FORM_QUICK_FILTERS_ALL_VALUE);
    const checkIsAllSelected = () => {
        if (multiple) {
            return !(field.value ?? []).length;
        }
        return field.value === constants_1.FORM_QUICK_FILTERS_ALL_VALUE || field.value == null;
    };
    const handleChipChange = (optionValue) => {
        if (optionValue === constants_1.FORM_QUICK_FILTERS_ALL_VALUE) {
            field.onChange(multiple ? [] : constants_1.FORM_QUICK_FILTERS_ALL_VALUE);
            return;
        }
        if (multiple) {
            const current = field.value ?? [];
            field.onChange(current.includes(optionValue)
                ? current.filter((v) => v !== optionValue)
                : [...current, optionValue]);
        }
        else {
            field.onChange(field.value === optionValue
                ? constants_1.FORM_QUICK_FILTERS_ALL_VALUE
                : optionValue);
        }
    };
    const isSelected = (optionValue) => {
        if (multiple) {
            return (field.value ?? []).includes(optionValue);
        }
        return field.value === optionValue;
    };
    const getOptionLabel = (value) => {
        const optionLabel = filterOptions.find((option) => option.value === value);
        return optionLabel?.label || value;
    };
    const getCounterLabel = (option) => {
        return option.counter ? ` (${option.counter})` : '';
    };
    return {
        field,
        filterOptions,
        checkIsAllSelected,
        handleChipChange,
        isSelected,
        label,
        allLabel,
        allCounter,
        multiple,
        maxCount,
        name,
        placeholder,
        control,
        getOptionLabel,
        getCounterLabel,
    };
};
exports.useLogic = useLogic;
