import { useMemo } from "react";
import { FileText, Plus } from "lucide-react";
import { Button } from "@/components/ui/button";

interface PageTreeProps {
  pages: Array<{
    id: string;
    parentPageId: string | null;
    title: string;
  }>;
  activePageId: string;
  onNavigate: (pageId: string) => void;
  onCreateChild: (parentPageId: string) => void;
}

interface TreeNode {
  id: string;
  title: string;
  children: TreeNode[];
}

export function PageTree({
  pages,
  activePageId,
  onNavigate,
  onCreateChild,
}: PageTreeProps) {
  const tree = useMemo(() => {
    const childrenMap = new Map<string | null, typeof pages>([]);
    for (const page of pages) {
      const key = page.parentPageId;
      const existing = childrenMap.get(key) ?? [];
      existing.push(page);
      childrenMap.set(key, existing);
    }

    function buildTree(parentId: string | null): TreeNode[] {
      const children = childrenMap.get(parentId) ?? [];
      return children.map((page) => ({
        id: page.id,
        title: page.title,
        children: buildTree(page.id),
      }));
    }

    return buildTree(null);
  }, [pages]);

  return (
    <div className="space-y-0.5">
      {tree.map((node) => (
        <PageTreeNode
          key={node.id}
          node={node}
          depth={0}
          activePageId={activePageId}
          onNavigate={onNavigate}
          onCreateChild={onCreateChild}
        />
      ))}
    </div>
  );
}

interface PageTreeNodeProps {
  node: TreeNode;
  depth: number;
  activePageId: string;
  onNavigate: (pageId: string) => void;
  onCreateChild: (parentPageId: string) => void;
}

function PageTreeNode({
  node,
  depth,
  activePageId,
  onNavigate,
  onCreateChild,
}: PageTreeNodeProps) {
  const isActive = node.id === activePageId;

  return (
    <div>
      <div
        className={`group flex items-center gap-1.5 rounded-sm px-2 py-1 text-sm cursor-pointer ${
          isActive
            ? "bg-accent text-accent-foreground"
            : "text-muted-foreground hover:bg-muted hover:text-foreground"
        }`}
        style={{ paddingLeft: `${depth * 12 + 8}px` }}
        onClick={() => onNavigate(node.id)}
      >
        <FileText className="h-3.5 w-3.5 shrink-0" />
        <span className="truncate flex-1">{node.title}</span>
        <Button
          variant="ghost"
          size="icon"
          className="h-5 w-5 opacity-0 group-hover:opacity-100 shrink-0"
          onClick={(e) => {
            e.stopPropagation();
            onCreateChild(node.id);
          }}
        >
          <Plus className="h-3 w-3" />
        </Button>
      </div>
      {node.children.map((child) => (
        <PageTreeNode
          key={child.id}
          node={child}
          depth={depth + 1}
          activePageId={activePageId}
          onNavigate={onNavigate}
          onCreateChild={onCreateChild}
        />
      ))}
    </div>
  );
}
