"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const useToggle_1 = require("../../../useToggle");
const utils_1 = require("./utils");
const useLogic = ({ item, value = [], level, isConfirmChildrenSelection, isInitialExpanded, expandedLevel, chainsToSelectedItem = [], disabledItems, onChange, isObjectMode, }) => {
    const { id, children } = item;
    const [isTooltipOpen, openTooltip, closeTooltip] = (0, useToggle_1.useToggle)();
    const childrenIds = (0, react_1.useMemo)(() => (0, utils_1.getAllChildrenId)(children, disabledItems), [children, disabledItems]);
    const isSelected = (0, utils_1.checkIsSelected)(value, id);
    const flatChainsToSelectedItem = (0, react_1.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 = (0, utils_1.getCurrentValueIds)(value);
        // Сбрасываем значение
        if (currentValueIds.includes(id)) {
            const hasSelectedChildren = childrenIds.some((childrenId) => currentValueIds.includes(childrenId));
            if (isConfirmChildrenSelection && hasSelectedChildren) {
                openTooltip();
            }
            const newValue = (0, utils_1.removeItem)(value, id);
            return onChange(newValue);
        }
        // Добавляем новый элемент
        const newValue = (0, utils_1.addItem)(value, item, isObjectMode);
        onChange(newValue);
        const isAllChildrenSelected = childrenIds.every((childrenId) => currentValueIds.includes(childrenId));
        if (isConfirmChildrenSelection && !isAllChildrenSelected) {
            openTooltip();
        }
    };
    const handleConfirmChildrenSelection = () => {
        const currentValueIds = (0, utils_1.getCurrentValueIds)(value);
        if (isSelected) {
            // Элемент выбран - выбираем все дочерние элементы
            const idsToAdd = childrenIds.filter((childrenId) => !currentValueIds.includes(childrenId));
            const newValue = (0, utils_1.addItemsByIds)(value, idsToAdd, children, isObjectMode);
            onChange(newValue);
        }
        else {
            // Элемент не выбран - исключаем все дочерние элементы
            const idsToRemove = childrenIds.filter((childrenId) => currentValueIds.includes(childrenId));
            const newValue = (0, utils_1.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,
    };
};
exports.useLogic = useLogic;
