import { useState } from 'react';
import { DocTreeNode } from '../api';

interface Props {
  nodes: DocTreeNode[];
  currentPath: string;
  onSelect: (path: string) => void;
  onCreate: (parentPath: string) => void;
  depth?: number;
}

export function DocTree({ nodes, currentPath, onSelect, onCreate, depth = 0 }: Props) {
  return (
    <div className="kb-tree" style={{ paddingLeft: depth > 0 ? 16 : 0 }}>
      {nodes.map(node => (
        <TreeNode
          key={node.path}
          node={node}
          currentPath={currentPath}
          onSelect={onSelect}
          onCreate={onCreate}
          depth={depth}
        />
      ))}
    </div>
  );
}

function TreeNode({
  node,
  currentPath,
  onSelect,
  onCreate,
  depth,
}: {
  node: DocTreeNode;
  currentPath: string;
  onSelect: (path: string) => void;
  onCreate: (parentPath: string) => void;
  depth: number;
}) {
  const [expanded, setExpanded] = useState(depth < 2);
  const isActive = node.path === currentPath;

  if (node.type === 'folder') {
    return (
      <div className="kb-tree-folder">
        <div
          className={`kb-tree-item kb-tree-folder-header ${expanded ? 'expanded' : ''}`}
          onClick={() => setExpanded(!expanded)}
        >
          <span className={`kb-tree-chevron ${expanded ? 'expanded' : ''}`}>›</span>
          <span className="kb-tree-folder-icon" aria-hidden="true" />
          <span className="kb-tree-name">{node.name}</span>
          <button
            className="kb-tree-add"
            onClick={e => {
              e.stopPropagation();
              onCreate(node.path);
            }}
            title="在此文件夹下新建文档"
          >
            +
          </button>
        </div>
        {expanded && node.children && (
          <DocTree
            nodes={node.children}
            currentPath={currentPath}
            onSelect={onSelect}
            onCreate={onCreate}
            depth={depth + 1}
          />
        )}
      </div>
    );
  }

  return (
    <div
      className={`kb-tree-item kb-tree-doc ${isActive ? 'active' : ''}`}
      onClick={() => onSelect(node.path)}
    >
      <span className="kb-tree-doc-icon" aria-hidden="true" />
      <span className="kb-tree-name">{node.name}</span>
    </div>
  );
}
