import { useCallback, useMemo, useState } from 'react';
import { classNames } from '../../utils/classNames';
import { autocompleteClassnames } from '../constants';
import { checkIsInputEmpty } from './utils';
export const useLogic = ({ value, isOptionEqualToValue: externalOptionEqualToValue, autoHighlight = true, freeSolo, options, multiple, className, loading, isLoadedDataError, loadedDataError = 'Ошибка загрузки данных', noOptionsText = 'Нет данных', onInputChange, }) => {
    const [innerInputValue, setInnerInputValue] = useState('');
    const isValueEmpty = checkIsInputEmpty(value);
    const isInnerInputValueNotEmpty = innerInputValue.length >= 1;
    const isOptionsAvailable = options.length > 0;
    const isPopperVisible = (loading && isOptionsAvailable) ||
        (!loading && !isOptionsAvailable && isInnerInputValueNotEmpty) ||
        isOptionsAvailable ||
        isLoadedDataError;
    const isOptionEqualToValue = useCallback((option, currentValue) => {
        if (externalOptionEqualToValue) {
            return externalOptionEqualToValue(option, currentValue);
        }
        return JSON.stringify(option) === JSON.stringify(currentValue);
    }, [externalOptionEqualToValue]);
    const handleInputChange = (event, currentValue, reason) => {
        onInputChange?.(event, currentValue, reason);
        if (!loading) {
            setInnerInputValue(currentValue);
        }
    };
    const classnames = useMemo(() => {
        return classNames(className, autocompleteClassnames.root, {
            [autocompleteClassnames.multiple]: multiple,
            [autocompleteClassnames.emptyValue]: isValueEmpty,
        });
    }, [multiple, isValueEmpty]);
    return {
        isValueEmpty,
        isPopperVisible,
        autocompleteProps: {
            className: classnames,
            isOptionEqualToValue,
            autoHighlight: freeSolo ? false : autoHighlight,
            noOptionsText: isLoadedDataError ? loadedDataError : noOptionsText,
            onInputChange: handleInputChange,
        },
    };
};
