"use client";

import { useMemo, useState } from "react";
import { MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

export interface TocEntry {
  id: string;
  title: string;
  level: number;
  numbering: string;
}

interface DocumentTocProps {
  entries: TocEntry[];
  visible: boolean;
  onJump: (id: string) => void;
  onClose?: () => void;
}

export function DocumentToc({ entries, visible, onJump, onClose }: DocumentTocProps) {
  const [maxLevel, setMaxLevel] = useState<number>(4);
  const [showFullTitle, setShowFullTitle] = useState(false);

  const filteredEntries = useMemo(() => entries.filter((entry) => entry.level <= maxLevel), [entries, maxLevel]);

  if (!visible || entries.length === 0) {
    return null;
  }

  return (
    <div className="pointer-events-none absolute right-0 top-0 z-10 hidden lg:block">
      <div className="pointer-events-auto mt-2 w-[min(320px,22vw)] min-w-40 max-w-80 max-h-[65vh] overflow-y-auto rounded-2xl border border-[#e4e4e7] bg-white/90 p-3 text-xs text-gray-600 shadow-lg backdrop-blur">
        <div className="mb-2 flex items-center justify-between">
          <div className="text-[11px] font-semibold text-gray-400">标题目录</div>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button
                type="button"
                className="inline-flex items-center justify-center rounded-md p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600"
                aria-label="标题目录菜单"
              >
                <MoreHorizontal className="h-4 w-4" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuRadioGroup value={String(maxLevel)} onValueChange={(v) => setMaxLevel(Number(v) || 4)}>
                <DropdownMenuRadioItem value="1">展开到 H1</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="2">展开到 H2</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="3">展开到 H3</DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="4">展开到 H4</DropdownMenuRadioItem>
              </DropdownMenuRadioGroup>
              <DropdownMenuSeparator />
              <DropdownMenuCheckboxItem checked={showFullTitle} onCheckedChange={(v) => setShowFullTitle(Boolean(v))}>
                显示完整标题
              </DropdownMenuCheckboxItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem onSelect={() => onClose?.()} disabled={!onClose}>
                关闭
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
        <ul className="space-y-1">
          {filteredEntries.map((entry) => (
            <li key={entry.id}>
              <button
                type="button"
                className={cn(
                  "w-full rounded-md px-2 py-1 text-left text-[11px] text-gray-500 transition-colors hover:bg-[#eef2ff] hover:text-[#2563eb]",
                  entry.level > 1 && "pl-4",
                  entry.level > 2 && "pl-6",
                  showFullTitle ? "whitespace-normal" : "truncate",
                )}
                onClick={() => onJump(entry.id)}
              >
                <span className="mr-2 font-mono text-[10px] text-gray-400">{entry.numbering}</span>
                {entry.title || "未命名"}
              </button>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
