"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { ChevronRight, FileText } from "lucide-react";
import { cn } from "@/lib/utils";

export interface NoteTreeNode {
  id: string;
  title: string;
  children: NoteTreeNode[];
}

interface TreeItemProps {
  node: NoteTreeNode;
  depth: number;
  activeNoteId?: string | null;
}

function TreeItem({ node, depth, activeNoteId }: TreeItemProps) {
  const router = useRouter();
  const [expanded, setExpanded] = useState(true);
  const hasChildren = node.children.length > 0;
  const isActive = node.id === activeNoteId;

  return (
    <div>
      <div
        onClick={() => router.push(`/notes/${node.id}`)}
        className={cn(
          "group flex cursor-pointer items-center gap-1 rounded-lg py-1.5 pr-1.5 text-[12.5px] transition-colors",
          isActive ? "bg-white/[0.08] text-white/90" : "text-white/50 hover:bg-white/[0.05] hover:text-white/75",
        )}
        style={{ paddingLeft: `${depth * 14 + 4}px` }}
      >
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            setExpanded((value) => !value);
          }}
          className={cn(
            "flex h-4 w-4 shrink-0 items-center justify-center rounded transition-transform",
            !hasChildren && "invisible",
          )}
        >
          <ChevronRight className={cn("h-3 w-3 transition-transform", expanded && "rotate-90")} />
        </button>
        <FileText className="h-3 w-3 shrink-0 text-white/25" />
        <span className="truncate">{node.title || "Untitled"}</span>
      </div>
      {hasChildren && expanded && (
        <div>
          {node.children.map((child) => (
            <TreeItem key={child.id} node={child} depth={depth + 1} activeNoteId={activeNoteId} />
          ))}
        </div>
      )}
    </div>
  );
}

interface NoteTreeProps {
  roots: NoteTreeNode[];
  activeNoteId?: string | null;
}

export function NoteTree({ roots, activeNoteId }: NoteTreeProps) {
  if (roots.length === 0) return null;

  return (
    <div className="space-y-0.5">
      {roots.map((root) => (
        <TreeItem key={root.id} node={root} depth={0} activeNoteId={activeNoteId} />
      ))}
    </div>
  );
}
