import { useMemo } from 'react';
import { useToggle } from '../../../useToggle';
import { addItem, addItemsByIds, checkIsSelected, getAllChildrenId, getCurrentValueIds, removeItem, removeItemsByIds, } from './utils';
export const useLogic = ({ item, value = [], level, isConfirmChildrenSelection, isInitialExpanded, expandedLevel, chainsToSelectedItem = [], disabledItems, onChange, isObjectMode, }) => {
    const { id, children } = item;
    const [isTooltipOpen, openTooltip, closeTooltip] = useToggle();
    const childrenIds = useMemo(() => getAllChildrenId(children, disabledItems), [children, disabledItems]);
    const isSelected = checkIsSelected(value, id);
    const flatChainsToSelectedItem = useMemo(() => chainsToSelectedItem?.reduce((acc, chain) => acc.concat(chain), []), [chainsToSelectedItem]);
    const isDefaultExpanded = flatChainsToSelectedItem?.includes(id) ||
        (isInitialExpanded && level <= expandedLevel - 1);
    const disabledItem = disabledItems?.find((formatDisableItem) => formatDisableItem.id === id);
    const isDisabled = Boolean(disabledItem);
    const disabledReason = disabledItem?.disabledReason;
    const nextLevel = level + 1;
    const handleChange = () => {
        if (isDisabled) {
            return;
        }
        const currentValueIds = getCurrentValueIds(value);
        // Сбрасываем значение
        if (currentValueIds.includes(id)) {
            const hasSelectedChildren = childrenIds.some((childrenId) => currentValueIds.includes(childrenId));
            if (isConfirmChildrenSelection && hasSelectedChildren) {
                openTooltip();
            }
            const newValue = removeItem(value, id);
            return onChange(newValue);
        }
        // Добавляем новый элемент
        const newValue = addItem(value, item, isObjectMode);
        onChange(newValue);
        const isAllChildrenSelected = childrenIds.every((childrenId) => currentValueIds.includes(childrenId));
        if (isConfirmChildrenSelection && !isAllChildrenSelected) {
            openTooltip();
        }
    };
    const handleConfirmChildrenSelection = () => {
        const currentValueIds = getCurrentValueIds(value);
        if (isSelected) {
            // Элемент выбран - выбираем все дочерние элементы
            const idsToAdd = childrenIds.filter((childrenId) => !currentValueIds.includes(childrenId));
            const newValue = addItemsByIds(value, idsToAdd, children, isObjectMode);
            onChange(newValue);
        }
        else {
            // Элемент не выбран - исключаем все дочерние элементы
            const idsToRemove = childrenIds.filter((childrenId) => currentValueIds.includes(childrenId));
            const newValue = removeItemsByIds(value, idsToRemove);
            onChange(newValue);
        }
        closeTooltip();
    };
    /**
     * Предотвращаем всплытие события, так как клик в области чекбокса или label вызывает обработчик на уровне всего item
     */
    const handleClick = (event) => {
        event.stopPropagation();
    };
    return {
        isSelected,
        isDefaultExpanded,
        isDisabled,
        disabledReason,
        nextLevel,
        formControlLabelProps: {
            disabled: isDisabled,
            onChange: handleChange,
            onClick: handleClick,
        },
        tooltipProps: {
            open: isTooltipOpen,
            onClose: closeTooltip,
        },
        confirmChildrenButtonProps: {
            onClick: handleConfirmChildrenSelection,
        },
        handleChange,
    };
};
