import { useAsyncOptions } from '../../useAsyncOptions';
import { DEFAULT_DELAY_MS, DEFAULT_EMPTY_OPTIONS_TEXT, DEFAULT_MIN_SEARCH_CHARACTERS, DEFAULT_NO_OPTIONS_TEXT, } from '../constants';
/* Стандартный фильтр. Необходим для правильного отображения опций, при асинхронном поиске
 * см. https://track.astral.ru/soft/browse/UIKIT-2823 */
const filterOptions = (options) => options;
export const useLogic = ({ fetchOptions, fetchDelayMs = DEFAULT_DELAY_MS, minSymbolsToFetch = DEFAULT_MIN_SEARCH_CHARACTERS, defaultValue, getOptionLabel, noOptionsText = DEFAULT_NO_OPTIONS_TEXT, onOpen, onInputChange, onDataLoadError, isLoadedDataError, isDisabled, isFullWidth, isSuccess, isError, isLoading, isRequired, ...restProps }) => {
    const { options, onInputChange: propsOnInputChange, onOpen: propsOnOpen, isLoadingData, isLoadingError, } = useAsyncOptions({
        fetchOptions,
        fetchDelayMs,
        minSymbolsToFetch,
        onDataLoadError,
    });
    const handleInputChange = (event, search, reason) => {
        onInputChange?.(event, search, reason);
        propsOnInputChange(search, reason);
    };
    const handleOpen = (event) => {
        const defaultSearch = defaultValue && getOptionLabel
            ? getOptionLabel(defaultValue)
            : '';
        propsOnOpen(defaultSearch, defaultValue);
        onOpen?.(event);
    };
    const emptyOptionsText = options.length === 0 ? noOptionsText : DEFAULT_EMPTY_OPTIONS_TEXT;
    return {
        autocompleteProps: {
            options,
            disabled: isDisabled,
            fullWidth: isFullWidth,
            loading: isLoading || isLoadingData,
            error: isError,
            required: isRequired,
            success: isSuccess,
            onOpen: handleOpen,
            noOptionsText: emptyOptionsText,
            onInputChange: handleInputChange,
            isLoadedDataError: isLoadedDataError ?? isLoadingError,
            getOptionLabel,
            defaultValue,
            filterOptions,
            ...restProps,
        },
    };
};
