import {
  disconnectLanguage,
  useFileConnections,
} from "@/store/file-connection";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
import { Button } from "../ui/button";
import { cn } from "@/lib/utils";

type Props = {
  projectId: string;
};

export function HeaderConnectionIndicator({ projectId }: Props) {
  const snap = useFileConnections(projectId);
  const list = Object.values(snap.connections);
  const hasAny = list.length > 0;

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          variant="outline"
          title={hasAny ? "已连线文件" : "未连线到任何文件"}
        >
          <span
            className={cn(
              "size-2 rounded-full",
              hasAny ? "bg-green-500" : "bg-red-500"
            )}
          ></span>
          {hasAny ? `已连线 ${list.length}` : "未连线"}
        </Button>
      </TooltipTrigger>
      <TooltipContent className="p-4">
        <div className="text-sm font-medium mb-2">连线状态</div>
        {list.length === 0 ? (
          <div className="text-sm text-muted-foreground">
            暂无连线。通过“导入 JSON”选择文件后将建立连线。
          </div>
        ) : (
          <div className="space-y-2">
            {list.map((c) => (
              <div
                key={c.language}
                className="flex items-start justify-between gap-2"
              >
                <div className="min-w-0">
                  <div className="text-sm font-medium truncate">
                    {c.language}
                  </div>
                  <div
                    className="text-xs text-muted-foreground truncate"
                    title={c.name}
                  >
                    {c.name}
                  </div>
                </div>
                <button
                  type="button"
                  className="px-2 h-7 rounded border text-xs hover:bg-accent"
                  onClick={() => disconnectLanguage(projectId, c.language)}
                >
                  断开
                </button>
              </div>
            ))}
            <div className="text-xs text-muted-foreground">
              注：出于隐私，浏览器不提供完整路径，仅显示文件名；刷新页面后连线不会自动恢复。
            </div>
          </div>
        )}
      </TooltipContent>
    </Tooltip>
  );
}
