import { useEffect, useMemo, useState, } from 'react';
import { deepMap } from '../../../utils/array';
import { findInTree } from './utils';
export const useLogic = ({ isOpen, isLoading, isLoadingError, initialValue, options, filterOptions, onChange, onClose, size = 'md', }) => {
    const [value, setValue] = useState(initialValue);
    const [searchValue, setSearchValue] = useState();
    useEffect(() => {
        setValue(initialValue);
    }, [initialValue]);
    useEffect(() => {
        // Очищаем поле поиска, если модальное окно закрыто
        if (!isOpen) {
            setSearchValue('');
        }
    }, [isOpen]);
    const filteredOptions = useMemo(() => searchValue ? findInTree(options, searchValue, filterOptions) : options, [options, searchValue]);
    const addIsForceExpandedFlag = (item) => {
        if (item.children) {
            return {
                ...item,
                options: { ...(item.options || {}), isForceExpanded: true },
            };
        }
        return item;
    };
    // Если строка поиска не пустая, то раскрываем все дерево в отфильтрованной выдаче
    const optionToRender = useMemo(() => searchValue
        ? 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,
        },
    };
};
