import { useEffect, useMemo, useState } from 'react';
import { useWatch } from 'react-hook-form';
import { useViewportType } from '../../../../components/useViewportType';
import { classNames } from '../../../../components/utils/classNames';
import { FORM_FILTERS_SEARCH_FIELD_ID } from '../../../FormFiltersSearchField/constants';
import { FORM_FILTERS_QUICK_FILTERS_ID } from '../../../FormQuickFilters/constants';
import { formFiltersClassnames } from '../../constants';
import { checkIsFilledValue, getFilledCount } from '../../utils';
export const useLogic = ({ form, onOpenModal, hasMainFilters, hasSecondaryFilters, hasSearch, hasQuickFilters, }) => {
    const { isMobile } = useViewportType();
    const formValues = useWatch({
        control: form.control,
    });
    const [searchName, setSearchName] = useState('');
    const [quickFiltersName, setQuickFiltersName] = useState('');
    useEffect(() => {
        const searchFieldName = document
            .getElementById(FORM_FILTERS_SEARCH_FIELD_ID)
            ?.getAttribute('name') || '';
        setSearchName(searchFieldName);
    }, [hasSearch]);
    useEffect(() => {
        const quickFiltersFieldName = document
            .getElementById(FORM_FILTERS_QUICK_FILTERS_ID)
            ?.getAttribute('name') || '';
        setQuickFiltersName(quickFiltersFieldName);
    }, [hasQuickFilters]);
    const getCounter = () => {
        const filledValuesCount = getFilledCount(formValues);
        // Исключаем поиск и quickFilters из счётчика — они видны на странице
        // quickFilters учитывается только на мобильных устройствах
        const searchValue = formValues?.[searchName];
        const quickFiltersValue = !isMobile && checkIsFilledValue(formValues?.[quickFiltersName]);
        return (filledValuesCount - (searchValue ? 1 : 0) - (quickFiltersValue ? 1 : 0));
    };
    const allFiltersButtonClassName = useMemo(() => {
        return classNames({
            [formFiltersClassnames.showAllFiltersButtonOnDesktop]: hasSecondaryFilters,
            [formFiltersClassnames.showAllFiltersButtonOnLaptop]: hasMainFilters || hasSecondaryFilters,
            [formFiltersClassnames.showAllFiltersButtonOnMobile]: hasMainFilters || hasSecondaryFilters,
            [formFiltersClassnames.withSearch]: hasSearch,
            [formFiltersClassnames.withoutSearch]: !hasSearch,
        });
    }, [hasMainFilters, hasSecondaryFilters, hasSearch]);
    return {
        allFiltersButtonClassName,
        counter: getCounter(),
        onOpenModal,
    };
};
