"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const array_1 = require("../../../utils/array");
const utils_1 = require("./utils");
const useLogic = ({ isOpen, isLoading, isLoadingError, initialValue, options, filterOptions, onChange, onClose, size = 'md', }) => {
    const [value, setValue] = (0, react_1.useState)(initialValue);
    const [searchValue, setSearchValue] = (0, react_1.useState)();
    (0, react_1.useEffect)(() => {
        setValue(initialValue);
    }, [initialValue]);
    (0, react_1.useEffect)(() => {
        // Очищаем поле поиска, если модальное окно закрыто
        if (!isOpen) {
            setSearchValue('');
        }
    }, [isOpen]);
    const filteredOptions = (0, react_1.useMemo)(() => searchValue ? (0, utils_1.findInTree)(options, searchValue, filterOptions) : options, [options, searchValue]);
    const addIsForceExpandedFlag = (item) => {
        if (item.children) {
            return {
                ...item,
                options: { ...(item.options || {}), isForceExpanded: true },
            };
        }
        return item;
    };
    // Если строка поиска не пустая, то раскрываем все дерево в отфильтрованной выдаче
    const optionToRender = (0, react_1.useMemo)(() => searchValue
        ? (0, array_1.deepMap)(filteredOptions, 'children', addIsForceExpandedFlag)
        : options, [filteredOptions, searchValue]);
    const handleChangeSearchField = (event) => setSearchValue(event.target.value);
    const handleChange = (newValue) => setValue(newValue);
    const handleClose = (event) => {
        setValue(initialValue);
        onClose?.(event, 'escapeKeyDown');
    };
    const handleCancel = (event) => {
        setValue(initialValue);
        onClose?.(event, 'escapeKeyDown');
    };
    const handleClick = (event) => {
        onChange?.(value);
        onClose?.(event, 'escapeKeyDown');
    };
    const isNoResult = Boolean(searchValue) && !filteredOptions.length;
    const isDisabledButton = !value || !value.length || isNoResult;
    return {
        isNoResult,
        modalProps: {
            onClose: handleClose,
            size,
        },
        searchFieldProps: {
            value: searchValue,
            disabled: isLoading || isLoadingError,
            onChange: handleChangeSearchField,
        },
        treeLikeListProps: {
            value,
            data: optionToRender,
            onChange: handleChange,
        },
        cancelButtonProps: {
            onClick: handleCancel,
        },
        confirmButtonProps: {
            disabled: isDisabledButton,
            onClick: handleClick,
        },
    };
};
exports.useLogic = useLogic;
