"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const MenuItem_1 = require("@mui/material/MenuItem");
const react_1 = require("react");
const MenuItem_2 = require("../../MenuItem");
const getNodeText_1 = require("../../utils/getNodeText");
const isSyncReactElement_1 = require("../../utils/isSyncReactElement");
const constants_1 = require("../constants");
const useLogic = ({ value, onChange, children, open: externalIsOpened, defaultOpen, multiple, isEnableAllSelection, isShowClearButton = true, valueOptions, onSelectAll, onUnselectAll, name, placeholder, onClose, onOpen, loading, }) => {
    const [isOpened, setOpened] = (0, react_1.useState)(!loading && (defaultOpen || externalIsOpened || false));
    const resetButtonRef = (0, react_1.useRef)(null);
    const optionsLength = Array.isArray(valueOptions)
        ? valueOptions?.length
        : null;
    const canUseAllSelection = multiple && isEnableAllSelection;
    const isValidValueArray = Array.isArray(value);
    const hasOptions = optionsLength !== null;
    // Вычисляем состояние "Выбрать все" на основе текущего значения
    const isSelectedAll = canUseAllSelection &&
        isValidValueArray &&
        hasOptions &&
        value.length === optionsLength;
    /**
     * Состояние чекбокса 'Выбрать все', когда есть выбранные опции, но не все
     */
    const isIndeterminate = canUseAllSelection &&
        isValidValueArray &&
        hasOptions &&
        value.length > 0 &&
        value.length < optionsLength;
    const openSelect = () => {
        if (loading) {
            return;
        }
        setOpened(true);
        onOpen?.();
    };
    const closeSelect = () => setOpened(false);
    const handleCloseSelect = (e) => {
        closeSelect();
        onClose?.(e);
    };
    const onClearAll = () => {
        const changeEvent = {
            target: {
                value: multiple ? [] : '',
                name,
            },
        };
        onChange?.call({}, changeEvent);
    };
    const isShowingClearButton = isShowClearButton &&
        value !== null &&
        value !== undefined &&
        !((Array.isArray(value) && value.length === 0) ||
            (typeof value === 'string' && value.length === 0));
    const isNoData = !react_1.Children.count(children);
    const createEvent = (eventValue) => {
        return {
            target: {
                value: eventValue,
                name,
            },
        };
    };
    const handleChangeOption = (event, child) => {
        const isSelectAllEvent = (0, react_1.isValidElement)(child) &&
            (0, isSyncReactElement_1.isSyncReactElement)(child) &&
            child.props.value === constants_1.SELECT_ALL_VALUE;
        const targetEvent = event;
        const targetValue = targetEvent.target.value;
        if (isSelectAllEvent) {
            if (isSelectedAll && !isIndeterminate) {
                if (onUnselectAll) {
                    return onUnselectAll();
                }
                return onChange?.(createEvent([]), child);
            }
            if (onSelectAll) {
                return onSelectAll();
            }
            return onChange?.(createEvent(valueOptions), child);
        }
        return onChange?.(createEvent(targetValue), child);
    };
    /**
     * onChange при изменении value через инпут, если value массив
     */
    const handleChangeArrayValue = (inputValue) => {
        if (!inputValue) {
            return onChange?.(createEvent([]), undefined);
        }
        // Вызов исходной функции с созданным событием
        return onChange?.(createEvent(inputValue), undefined);
    };
    const selectAllClassName = isSelectedAll || isIndeterminate ? MenuItem_1.menuItemClasses.selected : undefined;
    /**
     * Функция поиска в элементах MenuItem текста для отображения в Select
     */
    const findMenuItemsLabel = (nodes, selectedValue) => {
        const childrenArray = react_1.Children.toArray(nodes);
        //Проходим по массиву для нахождения выбранного элемента MenuItem
        for (const node of childrenArray) {
            if (!(0, react_1.isValidElement)(node)) {
                continue;
            }
            //Возвращаем текст из выбранного MenuItem
            if (node.type === MenuItem_2.MenuItem &&
                (0, isSyncReactElement_1.isSyncReactElement)(node) &&
                node.props.value === selectedValue) {
                return (0, getNodeText_1.getNodeText)(node.props.children);
            }
        }
        return null;
    };
    const isShowingPlaceholder = Boolean((value === '' || Array.isArray(value)) && !!placeholder);
    return {
        isOpened,
        isNoData,
        isShowingClearButton,
        resetButtonRef,
        openSelect,
        closeSelect: handleCloseSelect,
        onClearAll,
        isShowingSelectAll: canUseAllSelection,
        handleChangeOption,
        isSelectedAll,
        isIndeterminate,
        optionsLength,
        handleChangeArrayValue,
        selectAllClassName,
        findMenuItemsLabel,
        isShowingPlaceholder,
    };
};
exports.useLogic = useLogic;
