import { menuItemClasses } from '@mui/material/MenuItem';
import { Children, isValidElement, useRef, useState, } from 'react';
import { MenuItem } from '../../MenuItem';
import { getNodeText } from '../../utils/getNodeText';
import { isSyncReactElement } from '../../utils/isSyncReactElement';
import { SELECT_ALL_VALUE } from '../constants';
export const useLogic = ({ value, onChange, children, open: externalIsOpened, defaultOpen, multiple, isEnableAllSelection, isShowClearButton = true, valueOptions, onSelectAll, onUnselectAll, name, placeholder, onClose, onOpen, loading, }) => {
    const [isOpened, setOpened] = useState(!loading && (defaultOpen || externalIsOpened || false));
    const resetButtonRef = 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 = !Children.count(children);
    const createEvent = (eventValue) => {
        return {
            target: {
                value: eventValue,
                name,
            },
        };
    };
    const handleChangeOption = (event, child) => {
        const isSelectAllEvent = isValidElement(child) &&
            isSyncReactElement(child) &&
            child.props.value === 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 ? menuItemClasses.selected : undefined;
    /**
     * Функция поиска в элементах MenuItem текста для отображения в Select
     */
    const findMenuItemsLabel = (nodes, selectedValue) => {
        const childrenArray = Children.toArray(nodes);
        //Проходим по массиву для нахождения выбранного элемента MenuItem
        for (const node of childrenArray) {
            if (!isValidElement(node)) {
                continue;
            }
            //Возвращаем текст из выбранного MenuItem
            if (node.type === MenuItem &&
                isSyncReactElement(node) &&
                node.props.value === selectedValue) {
                return 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,
    };
};
