"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const useAsyncOptions_1 = require("../../useAsyncOptions");
const constants_1 = require("../constants");
const useLogic = ({ onBlur, isError, value, isDisabled, fetchDelayMs = constants_1.DEFAULT_DELAY_MS, fetchOptions, minSymbolsToFetch = constants_1.DEFAULT_MIN_SEARCH_CHARACTERS, onDataLoadError, onChange, loadingErrorMsg, treeProps, dialogProps, onShowUserHint, ...restInputProps }) => {
    const [isOpen, setOpen] = (0, react_1.useState)(false);
    const [isLoadingModal, setIsLoadingModal] = (0, react_1.useState)(false);
    const { options, isLoadingData, isLoadingError, onInputChange: propsOnInputChange, onOpen: propsOnOpen, onRetry: propsOnRetry, meta, } = (0, useAsyncOptions_1.useAsyncOptions)({
        fetchOptions,
        fetchDelayMs,
        minSymbolsToFetch,
        onDataLoadError,
    });
    (0, react_1.useEffect)(() => {
        if (!isLoadingData) {
            setIsLoadingModal(false);
        }
    }, [isLoadingData]);
    const onInputBlur = (event) => {
        // Если произошла потеря фокуса, но открылась окно поиска элемента, то не вызываем onBlur, так как произойдет преждевременная валидация
        if (!isOpen) {
            onBlur?.(event);
        }
    };
    const onOpen = () => {
        if (minSymbolsToFetch === 0) {
            setIsLoadingModal(true);
        }
        propsOnOpen(value?.label, value, true);
        setOpen(true);
    };
    const onKeyDown = (event) => {
        if (event.code === 'Enter') {
            setOpen(true);
        }
    };
    const valueToRender = value ? value.label : '';
    const onClose = (event) => {
        onBlur?.(event);
        setOpen(false);
    };
    const onRetry = (search = '') => {
        setIsLoadingModal(true);
        propsOnRetry(search);
    };
    const onInputChange = (search) => {
        if (isLoadingError) {
            setIsLoadingModal(true);
        }
        propsOnInputChange(search, 'input');
    };
    return {
        inputProps: {
            onBlur: onInputBlur,
            onClick: onOpen,
            onKeyDown,
            value: valueToRender,
            error: isError,
            disabled: isDisabled,
            onChange,
            ...restInputProps,
        },
        optionsModalProps: {
            isOpen,
            initialValue: value,
            meta,
            isLoading: isLoadingData,
            isLoadingError,
            loadingErrorMsg,
            treeProps,
            dialogProps: {
                ...dialogProps,
                onClose,
            },
            options,
            onRetry,
            onChange,
            onInputChange,
            isLoadingModal,
            onShowUserHint,
            minSymbolsToFetch,
        },
    };
};
exports.useLogic = useLogic;
