import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { normalizeVariables } from '../../utils/variableSerialization';
import Menu from '../../../../Menu';
import MenuItem from '../../../../Menu/components/MenuItem';
import { Box, InputAdornment, InputBase, Stack, useTheme } from '@mui/material';
import { IconChevronLeft, IconChevronRight, IconSearch, } from '@tabler/icons-react';
const collectLeaves = (nodes, parentKey, parentLabel) => {
    const results = [];
    for (const node of nodes) {
        const currentKey = parentKey ? `${parentKey}.${node.key}` : node.key;
        const currentLabel = parentLabel
            ? `${parentLabel} - ${node.label}`
            : node.label;
        if (node.children.length === 0) {
            results.push({
                token: currentKey,
                label: currentLabel,
                displayLabel: node.label,
            });
        }
        else {
            results.push(...collectLeaves(node.children, currentKey, currentLabel));
        }
    }
    return results;
};
const InsertVariableMenu = ({ anchorRef, open, onClose, onSelect, variables, }) => {
    const theme = useTheme();
    const { t } = useTranslation('material_hu_only');
    const [search, setSearch] = useState('');
    const [selectedCategory, setSelectedCategory] = useState(null);
    const normalizedVariables = useMemo(() => normalizeVariables(variables), [variables]);
    const query = search.toLowerCase().trim();
    const handleClose = () => {
        onClose();
        setSearch('');
        setSelectedCategory(null);
    };
    const handleSelect = (token, label) => {
        onSelect(token, label);
        setSearch('');
        setSelectedCategory(null);
    };
    const handleBack = () => {
        setSelectedCategory(null);
        setSearch('');
    };
    const categoryLeaves = useMemo(() => selectedCategory
        ? collectLeaves(selectedCategory.children, selectedCategory.key, selectedCategory.label)
        : [], [selectedCategory]);
    const searchResults = query
        ? categoryLeaves.filter(leaf => leaf.label.toLowerCase().includes(query))
        : [];
    const level2Header = selectedCategory ? (_jsxs(Stack, { children: [_jsxs(MenuItem, { onClick: handleBack, sx: {
                    gap: 1,
                    color: theme.palette.new.text.neutral.default,
                    typography: 'body2',
                    fontWeight: 600,
                }, children: [_jsx(IconChevronLeft, { size: 16 }), _jsx("span", { children: selectedCategory.label })] }), _jsx(InputBase, { autoFocus: true, value: search, onChange: e => setSearch(e.target.value), placeholder: t('top_bar_rich_text_editor.insert_variable_search_placeholder'), startAdornment: _jsx(InputAdornment, { position: "start", children: _jsx(IconSearch, { size: 16, color: theme.palette.new.text.neutral.lighter }) }), sx: {
                    px: 2,
                    py: 1,
                    typography: 'body2',
                    color: theme.palette.new.text.neutral.default,
                    width: 240,
                } })] })) : undefined;
    if (query && selectedCategory) {
        return (_jsx(Menu, { open: open, anchorEl: anchorRef.current, onClose: handleClose, fixedDimensions: true, position: "left", header: level2Header, sx: { '& .MuiList-root': { p: 0 } }, children: searchResults.length === 0 ? (_jsx(Stack, { sx: {
                    px: 2,
                    py: 1.5,
                    typography: 'body2',
                    color: theme.palette.new.text.neutral.lighter,
                }, children: t('top_bar_rich_text_editor.insert_variable_no_results') })) : (searchResults.map(leaf => (_jsx(MenuItem, { onClick: () => handleSelect(leaf.token, leaf.label), sx: {
                    px: 2,
                    gap: 1,
                    color: theme.palette.new.text.neutral.default,
                    typography: 'body2',
                }, children: _jsx("span", { children: leaf.displayLabel }) }, leaf.token)))) }));
    }
    if (selectedCategory) {
        return (_jsx(Menu, { open: open, anchorEl: anchorRef.current, onClose: handleClose, fixedDimensions: true, position: "left", header: level2Header, sx: { '& .MuiList-root': { p: 0 } }, children: categoryLeaves.map(leaf => (_jsx(MenuItem, { onClick: () => handleSelect(leaf.token, leaf.label), sx: {
                    px: 2,
                    gap: 1,
                    color: theme.palette.new.text.neutral.default,
                    typography: 'body2',
                }, children: _jsx("span", { children: leaf.displayLabel }) }, leaf.token))) }));
    }
    return (_jsx(Menu, { open: open, anchorEl: anchorRef.current, onClose: handleClose, fixedDimensions: true, position: "left", sx: { '& .MuiList-root': { p: 0 } }, children: normalizedVariables.map(category => (_jsxs(MenuItem, { onClick: () => setSelectedCategory(category), sx: {
                px: 2,
                gap: 1,
                justifyContent: 'space-between',
                color: theme.palette.new.text.neutral.default,
                typography: 'body2',
            }, children: [_jsx("span", { children: category.label }), _jsx(Box, { component: "span", sx: { display: 'inline-flex', flexShrink: 0 }, children: _jsx(IconChevronRight, { size: 16 }) })] }, category.key))) }));
};
export default InsertVariableMenu;
