import { useController } from 'react-hook-form';
import { FORM_QUICK_FILTERS_ALL_VALUE, FORM_QUICK_FILTERS_DEFAULT_ALL_LABEL, } from '../constants';
export const useLogic = ({ control, name, label, options, allLabel = FORM_QUICK_FILTERS_DEFAULT_ALL_LABEL, allCounter, multiple = false, maxCount, placeholder, }) => {
    const { field } = useController({ control, name });
    const filterOptions = options.filter((option) => option.value !== FORM_QUICK_FILTERS_ALL_VALUE);
    const checkIsAllSelected = () => {
        if (multiple) {
            return !(field.value ?? []).length;
        }
        return field.value === FORM_QUICK_FILTERS_ALL_VALUE || field.value == null;
    };
    const handleChipChange = (optionValue) => {
        if (optionValue === FORM_QUICK_FILTERS_ALL_VALUE) {
            field.onChange(multiple ? [] : 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
                ? 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,
    };
};
