import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { runHealthCheck, type HealthItem, type HealthReport } from "../../lib/commands";

// ── 状态图标 ──────────────────────────────────────────────────────────────────

function StatusIcon({ status }: { status: HealthItem["status"] }) {
  if (status === "ok") return (
    <svg className="w-4 h-4 text-green-500 shrink-0" viewBox="0 0 16 16" fill="currentColor">
      <path d="M8 16A8 8 0 108 0a8 8 0 000 16zm3.78-9.72a.75.75 0 00-1.06-1.06L6.75 9.19 5.28 7.72a.75.75 0 00-1.06 1.06l2 2a.75.75 0 001.06 0l4.5-4.5z"/>
    </svg>
  );
  if (status === "warn") return (
    <svg className="w-4 h-4 text-yellow-500 shrink-0" viewBox="0 0 16 16" fill="currentColor">
      <path d="M8.22 1.754a.25.25 0 00-.44 0L1.698 13.132a.25.25 0 00.22.368h12.164a.25.25 0 00.22-.368L8.22 1.754zm-1.763-.707c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0114.082 15H1.918a1.75 1.75 0 01-1.543-2.575L6.457 1.047zM9 11a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z"/>
    </svg>
  );
  if (status === "error") return (
    <svg className="w-4 h-4 text-red-500 shrink-0" viewBox="0 0 16 16" fill="currentColor">
      <path d="M2.343 13.657A8 8 0 1113.657 2.343 8 8 0 012.343 13.657zM6.03 4.97a.75.75 0 00-1.06 1.06L6.94 8 4.97 9.97a.75.75 0 101.06 1.06L8 9.06l1.97 1.97a.75.75 0 101.06-1.06L9.06 8l1.97-1.97a.75.75 0 10-1.06-1.06L8 6.94 6.03 4.97z"/>
    </svg>
  );
  return (
    <svg className="w-4 h-4 text-gray-300 shrink-0" viewBox="0 0 16 16" fill="currentColor">
      <path d="M8 0a8 8 0 100 16A8 8 0 008 0zM5 8a.75.75 0 01.75-.75h4.5a.75.75 0 010 1.5h-4.5A.75.75 0 015 8z"/>
    </svg>
  );
}

const STATUS_BG: Record<HealthItem["status"], string> = {
  ok:    "bg-green-50 border-green-100",
  warn:  "bg-yellow-50 border-yellow-100",
  error: "bg-red-50 border-red-100",
  skip:  "bg-gray-50 border-gray-100",
};

// ── 诊断报告生成 ──────────────────────────────────────────────────────────────

const escMd = (s: string) => s.replace(/\|/g, "\\|");

function buildMarkdownReport(report: HealthReport): string {
  const statusEmoji: Record<string, string> = { ok: "✅", warn: "⚠️", error: "❌", skip: "—" };
  const lines: string[] = [
    "# 炼境健康诊断报告",
    `检查时间：${report.checked_at}`,
    "",
    "## 基础设施健康",
    "| 检查项 | 状态 | 详情 |",
    "|--------|------|------|",
    ...report.items.map(i =>
      `| ${escMd(i.name)} | ${statusEmoji[i.status] ?? i.status} | ${escMd(i.detail ?? "-")} |`
    ),
    "",
    "## 质量指标",
  ];

  const q = report.quality;
  lines.push(`- 休眠项目（>30天未 push）：${q.dormant_projects.length} 个`);
  q.dormant_projects.forEach(p => lines.push(`  - ${p.name}（${p.days_since_push} 天）`));

  lines.push(`- 孤立项目（无分组 & 无 repo）：${q.orphaned_projects.length} 个`);
  q.orphaned_projects.forEach(p => lines.push(`  - ${p.name}`));

  lines.push(`- 注入异常产品组（近 7 天）：${q.groups_with_inject_warn.length} 个`);
  lines.push(`- 无本地路径项目：${q.projects_without_path} 个`);

  return lines.join("\n");
}

// ── 主页面 ────────────────────────────────────────────────────────────────────

export function HealthPage() {
  const [copied, setCopied] = useState(false);

  const { data: report, isFetching, refetch, dataUpdatedAt } = useQuery({
    queryKey: ["health-check"],
    queryFn: runHealthCheck,
    staleTime: Infinity,
    refetchOnWindowFocus: false,
  });

  const handleCopyReport = async () => {
    if (!report) return;
    try {
      await navigator.clipboard.writeText(buildMarkdownReport(report));
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      alert("复制失败，请手动选择文本后复制");
    }
  };

  const errorCount  = report?.items.filter(i => i.status === "error").length ?? 0;
  const warnCount   = report?.items.filter(i => i.status === "warn").length ?? 0;
  const lastChecked = dataUpdatedAt ? new Date(dataUpdatedAt).toLocaleTimeString("zh-CN") : null;

  return (
    <div className="flex flex-col h-full">
      {/* 顶栏 */}
      <div className="border-b border-gray-100 bg-white px-6 py-3 flex items-center gap-3 shrink-0">
        <h1 className="text-sm font-semibold text-gray-800">健康中心</h1>
        {lastChecked && (
          <span className="text-xs text-gray-400">上次检查 {lastChecked}</span>
        )}
        <div className="flex-1" />
        {report && (
          <button
            onClick={handleCopyReport}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs border border-gray-200 text-gray-600 hover:bg-gray-50 transition-colors"
          >
            <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="currentColor">
              <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 010 1.5h-1.5a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-1.5a.75.75 0 011.5 0v1.5A1.75 1.75 0 019.25 16h-7.5A1.75 1.75 0 010 14.25v-7.5z"/>
              <path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0114.25 11h-7.5A1.75 1.75 0 015 9.25v-7.5zm1.75-.25a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-7.5a.25.25 0 00-.25-.25h-7.5z"/>
            </svg>
            {copied ? "已复制" : "生成诊断报告"}
          </button>
        )}
        <button
          onClick={() => refetch()}
          disabled={isFetching}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-60 transition-colors"
        >
          <svg className={`w-3.5 h-3.5 ${isFetching ? "animate-spin" : ""}`} viewBox="0 0 16 16" fill="currentColor">
            <path d="M8 2.5a5.487 5.487 0 00-4.131 1.869l1.204 1.204A.25.25 0 014.896 6H1.25A.25.25 0 011 5.75V2.104a.25.25 0 01.427-.177l1.38 1.38A7.001 7.001 0 0114.95 7.16a.75.75 0 11-1.49.178A5.501 5.501 0 008 2.5zM1.705 8.005a.75.75 0 01.834.656 5.501 5.501 0 009.592 2.97l-1.204-1.204a.25.25 0 01.177-.427h3.646a.25.25 0 01.25.25v3.646a.25.25 0 01-.427.177l-1.38-1.38A7.001 7.001 0 011.05 8.84a.75.75 0 01.656-.834z"/>
          </svg>
          {isFetching ? "检查中…" : "立即检查"}
        </button>
      </div>

      {/* 内容区 */}
      <div className="flex-1 overflow-auto p-6">
        {!report && !isFetching && (
          <div className="flex flex-col items-center justify-center h-64 text-gray-400 gap-3">
            <svg className="w-10 h-10 text-gray-200" viewBox="0 0 16 16" fill="currentColor">
              <path d="M8 0a8 8 0 100 16A8 8 0 008 0zM1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0z"/>
            </svg>
            <p className="text-sm">点击「立即检查」开始诊断</p>
          </div>
        )}

        {isFetching && !report && (
          <div className="flex flex-col items-center justify-center h-64 text-gray-400 gap-3">
            <svg className="w-8 h-8 animate-spin text-blue-400" viewBox="0 0 16 16" fill="currentColor">
              <path d="M8 2.5a5.487 5.487 0 00-4.131 1.869l1.204 1.204A.25.25 0 014.896 6H1.25A.25.25 0 011 5.75V2.104a.25.25 0 01.427-.177l1.38 1.38A7.001 7.001 0 0114.95 7.16a.75.75 0 11-1.49.178A5.501 5.501 0 008 2.5z"/>
            </svg>
            <p className="text-sm">正在并行检查各项状态…</p>
          </div>
        )}

        {report && (
          <div className="grid grid-cols-2 gap-6 max-w-5xl">
            {/* 左列：基础设施健康项 */}
            <div className="space-y-3">
              <div className="flex items-center gap-2 mb-4">
                <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wide">基础设施健康</h2>
                {errorCount > 0 && (
                  <span className="px-1.5 py-0.5 rounded text-[10px] font-medium bg-red-100 text-red-600">{errorCount} 项异常</span>
                )}
                {errorCount === 0 && warnCount > 0 && (
                  <span className="px-1.5 py-0.5 rounded text-[10px] font-medium bg-yellow-100 text-yellow-600">{warnCount} 项警告</span>
                )}
                {errorCount === 0 && warnCount === 0 && (
                  <span className="px-1.5 py-0.5 rounded text-[10px] font-medium bg-green-100 text-green-600">全部正常</span>
                )}
              </div>

              {report.items.map((item) => (
                <div
                  key={item.id}
                  className={`rounded-xl border p-3.5 ${STATUS_BG[item.status]}`}
                >
                  <div className="flex items-center gap-2.5">
                    <StatusIcon status={item.status} />
                    <span className="text-sm font-medium text-gray-700">{item.name}</span>
                  </div>
                  {item.detail && (
                    <p className="mt-1.5 ml-7 text-xs text-gray-500 leading-relaxed">{item.detail}</p>
                  )}
                </div>
              ))}
            </div>

            {/* 右列：质量指标 */}
            <div className="space-y-3">
              <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-4">质量指标</h2>

              {/* 休眠项目 */}
              <QualityCard
                title="休眠项目"
                subtitle="> 30 天未 push 且有 repo"
                count={report.quality.dormant_projects.length}
                countColor={report.quality.dormant_projects.length > 0 ? "text-yellow-600" : "text-green-600"}
              >
                {report.quality.dormant_projects.length > 0 && (
                  <ul className="mt-2 space-y-1">
                    {report.quality.dormant_projects.map(p => (
                      <li key={p.id} className="flex items-center justify-between text-xs text-gray-500">
                        <span className="truncate">{p.name}</span>
                        <span className="shrink-0 ml-2 text-yellow-500 font-medium">{p.days_since_push} 天</span>
                      </li>
                    ))}
                  </ul>
                )}
              </QualityCard>

              {/* 孤立项目 */}
              <QualityCard
                title="孤立项目"
                subtitle="无分组 & 无 repo_url"
                count={report.quality.orphaned_projects.length}
                countColor={report.quality.orphaned_projects.length > 0 ? "text-yellow-600" : "text-green-600"}
              >
                {report.quality.orphaned_projects.length > 0 && (
                  <ul className="mt-2 space-y-1">
                    {report.quality.orphaned_projects.map(p => (
                      <li key={p.id} className="text-xs text-gray-500 truncate">{p.name}</li>
                    ))}
                  </ul>
                )}
              </QualityCard>

              {/* 注入异常组 */}
              <QualityCard
                title="MCP 注入异常"
                subtitle="近 7 天有 error/warn 的产品组"
                count={report.quality.groups_with_inject_warn.length}
                countColor={report.quality.groups_with_inject_warn.length > 0 ? "text-red-600" : "text-green-600"}
              >
                {report.quality.groups_with_inject_warn.length > 0 && (
                  <ul className="mt-2 space-y-1">
                    {report.quality.groups_with_inject_warn.map(id => (
                      <li key={id} className="text-xs text-gray-400 font-mono truncate">{id}</li>
                    ))}
                  </ul>
                )}
              </QualityCard>

              {/* 无路径项目数 */}
              <QualityCard
                title="无本地路径项目"
                subtitle="win_path 和 wsl_path 均为空"
                count={report.quality.projects_without_path}
                countColor={report.quality.projects_without_path > 0 ? "text-yellow-600" : "text-green-600"}
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── 质量指标卡片 ──────────────────────────────────────────────────────────────

function QualityCard({
  title, subtitle, count, countColor, children,
}: {
  title: string;
  subtitle: string;
  count: number;
  countColor: string;
  children?: React.ReactNode;
}) {
  return (
    <div className="rounded-xl border border-gray-100 bg-white p-3.5">
      <div className="flex items-start justify-between gap-2">
        <div>
          <p className="text-sm font-medium text-gray-700">{title}</p>
          <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>
        </div>
        <span className={`text-2xl font-bold tabular-nums shrink-0 ${countColor}`}>{count}</span>
      </div>
      {children}
    </div>
  );
}
