import { useEffect, useState } from "react";
import { Workflow, Database, Bookmark, FileText, Plus, Activity, Coins, Gauge, ArrowRight, ArrowUpRight, type LucideIcon } from "lucide-react";
import { statsOverview, type Overview, type RunSummary } 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 = 64;
  const h = 20;
  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 className="opacity-90">
      <polyline points={pts} fill="none" stroke={stroke} strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

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

// 能力入口：用「结果语言」描述，不暴露架构黑话。
const CAPS: { icon: LucideIcon; title: string; desc: string; to: ViewKey }[] = [
  { icon: Workflow, title: "智能体编排", desc: "把多步任务串成可复用的自动化工作流", to: "studio" },
  { icon: Database, title: "知识库问答", desc: "上传资料，让 AI 基于你的文档精准作答", to: "kb" },
  { icon: FileText, title: "报告生成", desc: "从大纲到成稿，一键产出结构化文档", to: "report" },
  { icon: Bookmark, title: "偏好记忆", desc: "记住你的习惯与历史，越用越懂你", to: "memory" },
];

const STATUS_LABEL: Record<string, { text: string; cls: string }> = {
  done: { text: "完成", cls: "text-success" },
  failed: { text: "失败", cls: "text-danger" }, timeout: { text: "超时", cls: "text-danger" }, rejected: { text: "已拒", cls: "text-danger" },
  waiting: { text: "待审", cls: "text-warn" },
  running: { text: "运行中", cls: "text-brand-400" }, submitted: { text: "已提交", cls: "text-brand-400" },
};

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)} 天前`;
}

// 一条最近运行。点击直达「运行」页对应那条 —— 光切页面还得让用户自己再找一遍。
// 有主题(报告类)就显示主题；否则退回 task_id：report_<hex> 这种 id 对用户没有任何意义。
function RunRow({ r, onOpen }: { r: RunSummary; onOpen: () => void }) {
  const s = STATUS_LABEL[r.status] ?? { text: r.status, cls: "text-slate-500" };
  return (
    <button onClick={onOpen} className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-ink-850">
      <span className={cn("h-1.5 w-1.5 flex-none rounded-full", s.cls.replace("text-", "bg-"))} />
      <span className={cn("flex-1 truncate text-xs", r.topic ? "text-slate-300" : "font-mono text-slate-400")}>
        {r.topic || r.task_id}
      </span>
      <span className={cn("text-[11px]", s.cls)}>{s.text}</span>
      <span className="w-16 text-right text-[11px] text-slate-600">{relTime(r.at)}</span>
    </button>
  );
}

function greet(): string {
  const h = new Date().getHours();
  return h < 6 ? "凌晨好" : h < 12 ? "早上好" : h < 14 ? "中午好" : h < 18 ? "下午好" : "晚上好";
}

// 工作台：商业级门面 —— 问候 + 主行动 + 关键指标 + 最近任务 + 快速开始（去基建、去黑话）。
export function Home({ onSelect, userName, spaceName }: { onSelect: (v: ViewKey, taskId?: string) => void; userName?: string; spaceName?: string }) {
  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}`);
  const hasRuns = !!ov && ov.recent_runs.length > 0;
  const quality = ov?.eval_count ? `${Math.round((ov.eval_avg ?? 0) * 100)}%` : "—";

  return (
    <div className="h-full overflow-auto p-8">
      <div className="mx-auto max-w-6xl">
        {/* 问候 + 主行动 */}
        <div className="flex flex-wrap items-end justify-between gap-4">
          <div>
            <h1 className="text-2xl font-semibold tracking-tight text-slate-100">
              {greet()}{userName ? `，${userName}` : ""}
            </h1>
            <p className="mt-1 text-sm text-slate-500">
              {spaceName ? <>工作区 · <span className="text-slate-400">{spaceName}</span> · </> : null}今天想做点什么？
            </p>
          </div>
          <Button variant="primary" size="md" icon={Plus} onClick={() => onSelect("studio")}>新建编排</Button>
        </div>

        {/* 关键指标 */}
        <div className="mt-7 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} />
          <Metric icon={Coins} label="今日用量" value={fmtTokens(ov?.tokens_today ?? 0)} sub={ov?.daily_budget ? `额度 ${fmtTokens(ov.daily_budget)}` : "未限额"} spark={tokenTrend} />
          <Metric icon={Database} label="知识库" value={`${ov?.kb_docs ?? 0}`} sub={`${ov?.kb_count ?? 0} 个库 · ${ov?.kb_docs ?? 0} 篇文档`} />
          <Metric icon={Gauge} label="回答质量" value={quality} sub={ov?.eval_count ? `近 ${ov.eval_count} 次评估` : "暂无评估"} />
        </div>

        {/* 最近任务 + 7 日趋势 */}
        <div className="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-[1.7fr_1fr]">
          <div className="rounded-xl border border-line bg-ink-900 p-4">
            <div className="mb-1 flex items-center justify-between px-2">
              <span className="text-sm font-medium text-slate-200">最近任务</span>
              {hasRuns && (
                <button onClick={() => onSelect("runs")} className="flex items-center gap-1 text-xs text-slate-400 transition hover:text-slate-200">
                  全部 <ArrowRight className="h-3 w-3" />
                </button>
              )}
            </div>
            {hasRuns ? (
              <div className="mt-1">{ov!.recent_runs.map((r) => <RunRow key={r.task_id} r={r} onOpen={() => onSelect("runs", r.task_id)} />)}</div>
            ) : (
              <div className="flex flex-col items-center gap-3 py-10 text-center">
                <div className="text-sm text-slate-400">还没有运行记录</div>
                <div className="max-w-xs text-xs leading-relaxed text-slate-600">搭一张编排、或上传资料建个知识库，任务跑起来后会在这里出现。</div>
                <Button size="sm" icon={Plus} onClick={() => onSelect("studio")}>从新建编排开始</Button>
              </div>
            )}
          </div>
          <div className="rounded-xl border border-line bg-ink-900 p-4">
            <div className="mb-3 text-sm font-medium text-slate-200">近 7 日任务量</div>
            <div className="flex h-28 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/60 transition-all hover:bg-brand" style={{ height: `${Math.max((d.count / maxTask) * 100, 3)}%` }} title={`${d.key}：${d.count} 次`} />
                  <span className="text-[10px] tabular-nums text-slate-600">{d.key.slice(-2)}</span>
                </div>
              ))}
              {!ov && <div className="flex-1 self-center text-center text-xs text-slate-600">加载中…</div>}
            </div>
          </div>
        </div>

        {/* 快速开始 */}
        <div className="mt-8">
          <div className="mb-3 text-xs font-medium uppercase tracking-widest text-slate-600">快速开始</div>
          <div className="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 flex flex-col rounded-xl border border-line bg-ink-850 p-4 text-left transition-colors hover:border-brand/40 hover:bg-ink-800">
                  <div className="flex items-center justify-between">
                    <Icon className="h-5 w-5 text-slate-300 transition-colors group-hover:text-brand-400" strokeWidth={1.8} />
                    <ArrowUpRight className="h-4 w-4 text-slate-700 transition-colors group-hover:text-slate-400" />
                  </div>
                  <div className="mt-3 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>
        {/* 原本这里还有一排「入库知识/生成报告/管理记忆」按钮，跳的目标和上面四张卡片
            完全重合 —— 同一页里同一个功能给两个入口，纯冗余，已删。 */}
      </div>
    </div>
  );
}
