import React, { useState } from 'react';
import { Button, Dropdown, Menu } from 'antd';
import { DownOutlined, EllipsisOutlined } from '@ant-design/icons';

// 树节点类型定义
type TreeNode = {
  id: string;
  name: string;
  children?: TreeNode[];
};

interface CheckPointTreeProps {
  treeData: TreeNode[];
  selectedKey: string | null;
  onSelect: (key: string) => void;
  onMoreAction?: (node: TreeNode) => void;
}

// 递归渲染树节点
const renderTreeNodes = (
  nodes: TreeNode[],
  selectedKey: string | null,
  onSelect: (key: string) => void,
  onMoreAction?: (node: TreeNode) => void,
) => {
  return nodes.map((node) => {
    const [expanded, setExpanded] = useState(true);
    const hasChildren = node.children && node.children.length > 0;
    return (
      <div key={node.id} className="tree-group">
        <div className="tree-group-title">
          {hasChildren && (
            <span
              className="tree-group-arrow"
              onClick={(e) => {
                e.stopPropagation();
                setExpanded(!expanded);
              }}
            >
              <DownOutlined rotate={expanded ? 0 : -90} />
            </span>
          )}
          <span
            className={
              selectedKey === node.id ? 'tree-item selected' : 'tree-item'
            }
            onClick={() => onSelect(node.id)}
          >
            {node.name}
          </span>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item
                  key="edit"
                  onClick={() => onMoreAction && onMoreAction(node)}
                >
                  编辑
                </Menu.Item>
                <Menu.Item
                  key="delete"
                  onClick={() => onMoreAction && onMoreAction(node)}
                >
                  删除
                </Menu.Item>
              </Menu>
            }
            trigger={['click']}
          >
            <EllipsisOutlined
              style={{ marginLeft: 8 }}
              onClick={(e) => e.stopPropagation()}
            />
          </Dropdown>
        </div>
        {hasChildren && expanded && (
          <div className="tree-group-children">
            {renderTreeNodes(
              node.children!,
              selectedKey,
              onSelect,
              onMoreAction,
            )}
          </div>
        )}
      </div>
    );
  });
};

/**
 * 查核要点左侧树形结构组件
 */
const CheckPointTree: React.FC<CheckPointTreeProps> = ({
  treeData,
  selectedKey,
  onSelect,
  onMoreAction,
}) => {
  return (
    <div className="check-point-tree">
      {renderTreeNodes(treeData, selectedKey, onSelect, onMoreAction)}
    </div>
  );
};

export default CheckPointTree;
