import React, { forwardRef, useState, useMemo } from "react";
import Tree from "rc-tree";
import cls from "classnames";
import { IconArrowWrapper, StyledArrow, base, StyledFolder, TitleWrapper, Title, ContentRight, Line, SpinnerStyled } from "./Tree.styles";
import { sizeToIconSize, traverseTree } from "./utils";
import { classes } from "./Tree.tokens";
/**
 * Многоуровневый раскрывающийся список в виде дерева.
 */ export const treeRoot = (Root)=>/*#__PURE__*/ forwardRef(({ items, arrowPlacement = 'left', virtual = true, height, itemHeight, size, view, variant, fullWidthItemSelection = false, multiple = false, defaultExpandAll = false, autoExpandParent = false, checkable = false, selectedKeys: outerSelectedKeys, checkedKeys, expandedKeys, defaultCheckedKeys, defaultExpandedKeys, defaultSelectedKeys, className, onTreeSelect, onTreeCheck, onTreeExpand, hasIcon = false, icon, renderTitle, singleLine = true, mode = 'default', draggable = false, onDragStart, onDragEnter, onDragOver, onDragLeave, onDragEnd, onDrop, allowDrop, loadData, onLoadData }, ref)=>{
        const [selected, setSelected] = useState(defaultSelectedKeys || []);
        const selectedKeys = outerSelectedKeys ?? selected;
        const isRadioMode = mode === 'radio' && !multiple;
        const handleSelect = (updatedSelectedKeys, info)=>{
            if (!multiple && isRadioMode && updatedSelectedKeys.length === 0) {
                return;
            }
            setSelected(updatedSelectedKeys);
            if (onTreeSelect) {
                onTreeSelect(updatedSelectedKeys, info);
            }
        };
        const invertedClass = arrowPlacement === 'right' ? classes.treeInverted : undefined;
        const itemFilledClass = fullWidthItemSelection ? classes.treeItemFilled : undefined;
        const radioModeClass = isRadioMode ? classes.treeRadioMode : undefined;
        const tightVariantClass = variant === 'tight' ? classes.treeTightVariant : undefined;
        // Проходимся по дереву и устанавливаем соответствующие классы для узлов дерева,
        // чтобы соблюсти иерархию вложенности в UI.
        const treeData = useMemo(()=>traverseTree(items, selectedKeys), [
            items,
            selectedKeys
        ]);
        return /*#__PURE__*/ React.createElement(Root, {
            view: view,
            size: size,
            variant: variant,
            ref: ref,
            items: items
        }, /*#__PURE__*/ React.createElement(Tree, {
            loadData: loadData,
            onLoad: onLoadData,
            height: height,
            itemHeight: itemHeight,
            virtual: virtual,
            multiple: multiple,
            checkable: checkable,
            className: cls(className, invertedClass, itemFilledClass, radioModeClass, tightVariantClass),
            defaultExpandAll: defaultExpandAll,
            autoExpandParent: autoExpandParent,
            style: {
                border: '1px solid #000'
            },
            treeData: treeData,
            selectedKeys: selectedKeys,
            ...checkedKeys !== undefined ? {
                checkedKeys
            } : {},
            ...expandedKeys !== undefined ? {
                expandedKeys
            } : {},
            defaultCheckedKeys: defaultCheckedKeys,
            defaultExpandedKeys: defaultExpandedKeys,
            onSelect: handleSelect,
            // Тайп кастинг для упрощения API
            onCheck: onTreeCheck,
            onExpand: onTreeExpand,
            switcherIcon: (node)=>{
                if (node.isLeaf) {
                    return null;
                }
                if (node.loading) {
                    return /*#__PURE__*/ React.createElement(SpinnerStyled, null);
                }
                return /*#__PURE__*/ React.createElement(IconArrowWrapper, null, /*#__PURE__*/ React.createElement(StyledArrow, {
                    size: sizeToIconSize(size, variant),
                    color: "inherit",
                    className: "arrow"
                }));
            },
            icon: hasIcon && (icon || /*#__PURE__*/ React.createElement(StyledFolder, {
                size: sizeToIconSize(size, variant),
                color: "inherit"
            })),
            titleRender: (item)=>/*#__PURE__*/ React.createElement(TitleWrapper, {
                    fullWidthItemSelection: fullWidthItemSelection,
                    arrowPlacement: arrowPlacement,
                    singleLine: singleLine
                }, /*#__PURE__*/ React.createElement(Title, {
                    singleLine: singleLine
                }, renderTitle ? renderTitle(item) : typeof item.title === 'function' ? item.title(item) : item.title), item.contentRight && /*#__PURE__*/ React.createElement(ContentRight, null, item.contentRight)),
            draggable: draggable,
            onDragStart: onDragStart,
            onDragEnter: onDragEnter,
            onDragOver: onDragOver,
            onDragLeave: onDragLeave,
            onDragEnd: onDragEnd,
            onDrop: onDrop,
            allowDrop: allowDrop,
            dropIndicatorRender: (props)=>{
                const offset = 0;
                const { dropPosition, dropLevelOffset, indent } = props;
                const left = -dropLevelOffset * indent + offset;
                const style = {};
                if (dropPosition === 0) {
                    style.left = indent + offset;
                }
                return /*#__PURE__*/ React.createElement(Line, {
                    style: style,
                    left: left,
                    dropPosition: dropPosition,
                    variant: variant
                });
            }
        }));
    });
export const treeConfig = {
    name: 'Tree',
    tag: 'div',
    layout: treeRoot,
    base,
    variations: {},
    defaults: {
        view: 'default',
        size: 'm'
    }
};
