import { useEffect, useState } from "react";
import { Workflow, Database, Bookmark, FileText, Plus, Upload, Activity, Coins, Gauge, ArrowRight, type LucideIcon } from "lucide-react";
import { statsOverview, type Overview, type RecentRun } from "../lib/api";
import type { ViewKey } from "../shell/LeftNav";
import { Button, cn } from "../ui";

// 迷你火花线：把一串数值画成 SVG 折线（仪表盘趋势）。
function Spark({ data, stroke }: { data: number[]; stroke: string }) {
  if (data.length < 2) return null;
  const max = Math.max(...data, 1);
  const min = Math.min(...data, 0);
  const span = max - min || 1;
  const w = 60;
  const h = 18;
  const pts = data
    .map((v, i) => `${(i / (data.length - 1)) * w},${h - ((v - min) / span) * (h - 2) - 1}`)
    .join(" ");
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} aria-hidden>
      <polyline points={pts} fill="none" stroke={stroke} strokeWidth={1.5} strokeLinejoin="round" />
    </svg>
  );
}

function Metric({ icon: Icon, label, value, sub, spark, sparkColor, accent }: {
  icon: LucideIcon; label: string; value: string; sub: string;
  spark?: number[]; sparkColor?: string; accent?: string;
}) {
  return (
    <div className="rounded-lg border border-line bg-ink-850 p-4">
      <div className="flex items-center justify-between">
        <span className="text-xs text-slate-500">{label}</span>
        <Icon className="h-4 w-4 text-slate-600" strokeWidth={1.8} />
      </div>
      <div className={cn("mt-1 text-2xl font-semibold tabular-nums", accent ?? "text-slate-100")}>{value}</div>
      <div className="mt-1.5 flex items-center justify-between gap-2">
        <span className="text-[11px] text-slate-500">{sub}</span>
        {spark && spark.some((v) => v > 0) ? <Spark data={spark} stroke={sparkColor ?? "#a78bfa"} /> : null}
      </div>
    </div>
  );
}

const CAPS: { icon: LucideIcon; title: string; desc: string; to: ViewKey; color: string }[] = [
  { icon: Workflow, title: "Agent 编排", desc: "画布 → Eino 动态图 → 流式执行", to: "studio", color: "text-brand-400" },
  { icon: Database, title: "RAG 知识库", desc: "向量 / 全文 / 图谱 三路混合检索", to: "kb", color: "text-accent-400" },
  { icon: FileText, title: "报告生成", desc: "规划 → 分章并行 → 渲染 Word", to: "report", color: "text-indigo-300" },
  { icon: Bookmark, title: "偏好记忆", desc: "画像 + 多轮历史", to: "memory", color: "text-success" },
];

const STATUS_DOT: Record<string, string> = {
  done: "bg-success",
  failed: "bg-danger", timeout: "bg-danger", rejected: "bg-danger",
  waiting: "bg-warn",
  running: "bg-brand", submitted: "bg-brand",
};

const SERVICE_LABEL: Record<string, string> = {
  gateway: "网关", nats: "总线", db: "PG", redis: "Redis", milvus: "Milvus", neo4j: "Neo4j",
};

function relTime(iso: string): string {
  const d = Date.now() - new Date(iso).getTime();
  if (d < 60_000) return "刚刚";
  if (d < 3_600_000) return `${Math.floor(d / 60_000)} 分钟前`;
  if (d < 86_400_000) return `${Math.floor(d / 3_600_000)} 小时前`;
  return `${Math.floor(d / 86_400_000)} 天前`;
}

function RunRow({ r }: { r: RecentRun }) {
  return (
    <div className="flex items-center gap-3 border-b border-line/60 py-2 last:border-0">
      <span className={cn("h-1.5 w-1.5 flex-none rounded-full", STATUS_DOT[r.status] ?? "bg-ink-600")} />
      <span className="flex-1 truncate font-mono text-xs text-slate-300">{r.task_id}</span>
      <span className="text-[11px] text-slate-500">{r.status}</span>
      <span className="w-16 text-right text-[11px] text-slate-600">{relTime(r.at)}</span>
    </div>
  );
}

// 工作台：实时驾驶舱（指标 + 趋势 + 近期运行 + 服务健康 + 快捷动作）。
export function Home({ onSelect }: { onSelect: (v: ViewKey) => void }) {
  const [ov, setOv] = useState<Overview | null>(null);
  useEffect(() => {
    let alive = true;
    const load = () => statsOverview().then((d) => alive && setOv(d)).catch(() => {});
    load();
    const id = setInterval(load, 5000);
    return () => { alive = false; clearInterval(id); };
  }, []);

  const taskTrend = ov?.task_trend.map((d) => d.count) ?? [];
  const tokenTrend = ov?.token_trend.map((d) => d.count) ?? [];
  const maxTask = Math.max(...taskTrend, 1);
  const fmtTokens = (n: number) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}K` : `${n}`);

  return (
    <div className="h-full overflow-auto p-8">
      <div className="mx-auto max-w-6xl">
        {/* 头部 */}
        <div className="flex items-center gap-3">
          <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-brand to-accent text-lg font-bold text-white shadow-glow">S</div>
          <div className="flex-1">
            <h1 className="brand-gradient text-2xl font-bold leading-tight">工作台</h1>
            <p className="text-sm text-slate-500">实时概览 · 编排 / 知识库 / 报告 / 记忆</p>
          </div>
          <span className="flex items-center gap-1.5 rounded-full border border-line bg-ink-850 px-3 py-1 text-[11px] text-slate-500">
            <span className={cn("h-1.5 w-1.5 rounded-full", ov?.services.gateway ? "bg-success" : "bg-danger")} />
            {ov?.services.gateway ? "实时" : "连接中"}
          </span>
        </div>

        {/* 指标卡 */}
        <div className="mt-6 grid grid-cols-2 gap-3 lg:grid-cols-4">
          <Metric icon={Activity} label="今日任务" value={`${ov?.tasks_today ?? 0}`} sub={`累计 ${ov?.tasks_total ?? 0}`}
            spark={taskTrend} sparkColor="#34d399" accent="text-brand-400" />
          <Metric icon={Coins} label="今日 Token" value={fmtTokens(ov?.tokens_today ?? 0)}
            sub={ov?.daily_budget ? `预算 ${fmtTokens(ov.daily_budget)}` : "未限额"} spark={tokenTrend} sparkColor="#a78bfa" accent="text-accent-400" />
          <Metric icon={Gauge} label="评测均分" value={(ov?.eval_avg ?? 0).toFixed(2)}
            sub={`忠实 ${(ov?.faithful_avg ?? 0).toFixed(2)} · ${ov?.eval_count ?? 0} 次`} accent="text-success" />
          <Metric icon={Database} label="知识库" value={`${ov?.kb_docs ?? 0}`} sub={`${ov?.kb_count ?? 0} 库 · 三路检索`} accent="text-indigo-300" />
        </div>

        {/* 近期运行 + 7 日趋势 */}
        <div className="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-[1.6fr_1fr]">
          <div className="rounded-lg border border-line bg-ink-900 p-4">
            <div className="mb-2 flex items-center justify-between">
              <span className="text-sm font-medium text-slate-300">近期运行</span>
              <button onClick={() => onSelect("runs")} className="flex items-center gap-1 text-xs text-brand-400 transition hover:opacity-80">
                全部 <ArrowRight className="h-3 w-3" />
              </button>
            </div>
            {ov && ov.recent_runs.length > 0 ? (
              ov.recent_runs.map((r) => <RunRow key={r.task_id} r={r} />)
            ) : (
              <div className="py-8 text-center text-xs text-slate-600">暂无运行记录</div>
            )}
          </div>
          <div className="rounded-lg border border-line bg-ink-900 p-4">
            <div className="mb-3 text-sm font-medium text-slate-300">7 日任务量</div>
            <div className="flex h-24 items-end gap-2">
              {(ov?.task_trend ?? []).map((d, i) => (
                <div key={i} className="flex flex-1 flex-col items-center gap-1.5">
                  <div className="w-full rounded-t bg-brand/70 transition-all" style={{ height: `${Math.max((d.count / maxTask) * 100, 4)}%` }} title={`${d.count}`} />
                  <span className="text-[10px] text-slate-600">{d.key.slice(-2)}</span>
                </div>
              ))}
              {!ov && <div className="flex-1 text-center text-xs text-slate-600">加载中…</div>}
            </div>
          </div>
        </div>

        {/* 服务健康灯带 */}
        <div className="mt-4 flex flex-wrap items-center gap-x-5 gap-y-2 rounded-lg border border-line bg-ink-850 px-4 py-2.5">
          <span className="text-xs text-slate-500">服务</span>
          {Object.entries(SERVICE_LABEL).map(([k, label]) => (
            <span key={k} className="flex items-center gap-1.5 text-xs text-slate-400">
              <span className={cn("h-1.5 w-1.5 rounded-full", ov?.services[k] ? "bg-success" : "bg-ink-600")} />
              {label}
            </span>
          ))}
        </div>

        {/* 能力入口 */}
        <div className="mt-6 grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-4">
          {CAPS.map((c) => {
            const Icon = c.icon;
            return (
              <button key={c.to} onClick={() => onSelect(c.to)}
                className="group rounded-lg border border-line bg-ink-850 p-4 text-left transition hover:border-brand/50 hover:bg-ink-800">
                <Icon className={cn("h-5 w-5", c.color)} strokeWidth={1.8} />
                <div className="mt-2.5 text-sm font-medium text-slate-100">{c.title}</div>
                <div className="mt-1 text-xs leading-relaxed text-slate-500">{c.desc}</div>
              </button>
            );
          })}
        </div>

        {/* 快捷动作 */}
        <div className="mt-4 flex flex-wrap gap-2">
          <Button variant="primary" size="sm" icon={Plus} onClick={() => onSelect("studio")}>新建编排</Button>
          <Button size="sm" icon={Upload} onClick={() => onSelect("kb")}>入库知识</Button>
          <Button size="sm" icon={FileText} onClick={() => onSelect("report")}>生成报告</Button>
          <Button size="sm" icon={Bookmark} onClick={() => onSelect("memory")}>管理记忆</Button>
        </div>
      </div>
    </div>
  );
}
