"use client";

import Link from "next/link";
import { useParams, useSelectedLayoutSegments } from "next/navigation";
import { ChevronRight, MoreHorizontal, Sparkles, Star } from "lucide-react";
import { useConvexAuth, useMutation, useQuery } from "convex/react";
import type { DocumentRecord } from "@/lib/documents";
import { findBreadcrumb } from "@/lib/documents";
import { useBackendHealth } from "@/hooks/use-backend-health";
import { cn } from "@/lib/utils";
import { usePageLayoutStore } from "@/store/page-layout";
import { useAiAgentUiStore } from "@/store/ai-agent-ui";
import { api } from "@/lib/convex/api";

interface BreadcrumbProps {
  documents: DocumentRecord[];
}

export function Breadcrumb({ documents }: BreadcrumbProps) {
  const { isAuthenticated } = useConvexAuth();
  const segments = useSelectedLayoutSegments();
  const params = useParams<{ id?: string }>();
  const paramId = typeof params?.id === "string" ? params.id : "";
  const activeId = paramId || segments?.[1] || "";
  const path = findBreadcrumb(documents, activeId);
  const showInspector = usePageLayoutStore((state) => state.showInspector);
  const toggleInspector = usePageLayoutStore((state) => state.toggleInspector);
  const backendStatus = useBackendHealth();
  const documentAgentAvailable = useAiAgentUiStore((s) => s.documentAgentAvailable);
  const toggleDocumentAgentOpen = useAiAgentUiStore((s) => s.toggleDocumentAgentOpen);
  const isStarred = useQuery(
    api.documentStars.isStarred,
    activeId && isAuthenticated ? { documentId: activeId } : "skip",
  );
  const toggleStar = useMutation(api.documentStars.toggle);

  // 新建页面后，侧边栏数据可能还没同步到 layout（SSR）注入的 documents，导致 findBreadcrumb 暂时为空。
  // 这里用 activeId 兜底，避免右上角“收藏/更多”按钮消失。
  if (!activeId) {
    return <div className="text-sm text-gray-400">请选择一个页面</div>;
  }
  const displayPath: Array<Pick<DocumentRecord, "id" | "title">> = path.length
    ? path
    : [{ id: activeId, title: "无标题" }];

  return (
    <div className="flex flex-1 items-center justify-between">
      <nav className="flex items-center text-sm text-wolai-text-secondary">
        {displayPath.map((node, index) => {
          const isLast = index === displayPath.length - 1;
          return (
            <span key={node.id} className="flex items-center">
              {index > 0 && <ChevronRight className="mx-1 h-4 w-4 text-gray-400" />}
              {isLast ? (
                <span className="font-medium text-wolai-text-primary">{node.title || "无标题"}</span>
              ) : (
                <Link
                  href={`/documents/${node.id}`}
                  className="hover:bg-wolai-bg-hover hover:text-wolai-text-primary px-1.5 py-0.5 rounded cursor-pointer transition-colors"
                >
                  {node.title || "无标题"}
                </Link>
              )}
            </span>
          );
        })}
      </nav>
      <div className="flex items-center gap-2 text-wolai-text-secondary">
        <span
          className={cn(
            "h-2 w-2 rounded-full",
            backendStatus === "ok" ? "bg-green-500" : "bg-red-500",
          )}
          title={`后端连接：${
            backendStatus === "ok"
              ? "正常"
              : backendStatus === "disabled"
                ? "未配置"
                : backendStatus === "error"
                  ? "异常"
                  : "检测中"
          }`}
          aria-label="后端连接状态"
        />
        <button
          type="button"
          className={cn(
            "hover:bg-wolai-bg-hover hover:text-wolai-text-primary rounded-full px-3 py-1 text-sm transition-colors",
            !documentAgentAvailable && "cursor-not-allowed opacity-50",
          )}
          onClick={() => toggleDocumentAgentOpen()}
          disabled={!documentAgentAvailable}
          title={documentAgentAvailable ? "打开页面 AI" : "仅在页面编辑区可用"}
        >
          <Sparkles className="mr-1 inline h-4 w-4" />
          AI
        </button>
        <button
          type="button"
          className="hover:bg-wolai-bg-hover hover:text-wolai-text-primary rounded-full px-3 py-1 text-sm transition-colors"
          onClick={() => void toggleStar({ documentId: activeId })}
          disabled={!activeId || !isAuthenticated}
        >
          <Star
            className={`mr-1 inline h-4 w-4 ${isStarred ? "text-[#f5a623]" : ""}`}
            fill={isStarred ? "currentColor" : "none"}
          />
          收藏
        </button>
        <button
          type="button"
          className="hover:bg-wolai-bg-hover hover:text-wolai-text-primary rounded-full p-2 transition-colors"
          onClick={toggleInspector}
          aria-label={showInspector ? "隐藏页面选项" : "显示页面选项"}
          title={showInspector ? "隐藏页面选项" : "显示页面选项"}
        >
          <MoreHorizontal className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
}
