import { useEffect, useMemo, useState, } from 'react';
import { deepMap } from '../../../utils/array';
export const useLogic = ({ isOpen, initialValue, options, onChange, dialogProps, onInputChange, onRetry, meta, onShowUserHint, isLoadingModal, minSymbolsToFetch = 0, isLoading, isLoadingError, loadingErrorMsg, treeProps, }) => {
    const [value, setValue] = useState(initialValue);
    const [searchValue, setSearchValue] = useState();
    const { onClose, ...restDialogProps } = dialogProps;
    useEffect(() => {
        setValue(initialValue);
    }, [initialValue]);
    useEffect(() => {
        // В поле ввода вставляем выбранное значение или пустую строку для запроса на открытие модального окна
        if (isOpen) {
            setSearchValue(value?.label ?? '');
        }
    }, [isOpen]);
    const addIsForceExpandedFlag = (item) => {
        if (item.children) {
            return {
                ...item,
                options: { ...(item.options || {}), isForceExpanded: true },
            };
        }
        return item;
    };
    // Если строка поиска не пустая и загрузки нет, то раскрываем все дерево в отфильтрованной выдаче
    const optionToRender = useMemo(() => searchValue && !isLoading
        ? deepMap(options, 'children', addIsForceExpandedFlag)
        : options, [options, searchValue, isLoading]);
    const handleChangeSearchField = (event) => {
        setSearchValue(event.target.value);
        onInputChange(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) && !options.length;
    const isDisabledButton = !value || isNoResult;
    const handleRetry = () => {
        onRetry?.(searchValue);
    };
    const isShowUserHint = onShowUserHint?.(options) || meta?.isAllDataLoaded;
    const isShowModalLoader = isLoadingModal && options.length === 0;
    const isShowSearchFieldLoader = (isLoading && !isLoadingModal) ||
        (isLoading && isLoadingModal && options.length > 0);
    const isShowSearchSuggestion = Boolean((!searchValue && minSymbolsToFetch > 0) ||
        (searchValue && searchValue.length < minSymbolsToFetch));
    return {
        isShowModalLoader,
        isShowSearchFieldLoader,
        isNoResult,
        handleRetry,
        isShowUserHint,
        isShowSearchSuggestion,
        treeProps,
        loadingErrorMsg,
        isLoadingError,
        modalProps: {
            onClose: handleClose,
            disableRestoreFocus: true,
            open: isOpen,
            size: 'md',
            ...restDialogProps,
        },
        searchFieldProps: {
            value: searchValue,
            onChange: handleChangeSearchField,
        },
        treeListProps: {
            value,
            data: optionToRender,
            onChange: handleChange,
            isObjectMode: true,
        },
        cancelButtonProps: {
            onClick: handleCancel,
        },
        confirmButtonProps: {
            disabled: isDisabledButton,
            onClick: handleClick,
        },
    };
};
