import { prisma } from "@/lib/db";
import { AGENT_LABEL, type AgentKind } from "@/lib/agents";
import Link from "next/link";

export const dynamic = "force-dynamic";

export default async function DashboardPage() {
  const [agents, hosts, events] = await Promise.all([
    prisma.agent.findMany({ include: { host: true }, orderBy: { updatedAt: "desc" } }),
    prisma.host.count(),
    prisma.agentEvent.findMany({ orderBy: { createdAt: "desc" }, take: 12, include: { agent: true } }),
  ]);

  const byKind: Record<AgentKind, number> = { opencode: 0, openclaw: 0, hermes: 0 };
  let running = 0, stopped = 0, errored = 0;
  for (const a of agents) {
    byKind[a.kind as AgentKind] = (byKind[a.kind as AgentKind] ?? 0) + 1;
    if (a.status === "running") running++;
    else if (a.status === "stopped") stopped++;
    else if (a.status === "error") errored++;
  }

  return (
    <div className="space-y-7">
      <header className="flex items-end justify-between flex-wrap gap-3">
        <div>
          <div className="text-[11px] uppercase tracking-[0.18em] text-muted mb-1">Tổng quan</div>
          <h1 className="text-3xl font-semibold tracking-tight h-gradient">Trạm điều khiển agent</h1>
          <div className="text-sm text-muted mt-1">Theo dõi sức khỏe các agent và host realtime.</div>
        </div>
        <div className="flex gap-2">
          <Link href="/agents/new" className="btn btn-primary">+ Tạo agent mới</Link>
        </div>
      </header>

      <div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
        <StatCard label="Tổng agent" value={agents.length} hint={`trên ${hosts} host`} accent="violet" />
        <StatCard label="Đang chạy" value={running} accent="ok" pulse />
        <StatCard label="Đã dừng" value={stopped} accent="muted" />
        <StatCard label="Lỗi" value={errored} accent={errored ? "bad" : "muted"} />
        <StatCard label="Host" value={hosts} accent="cyan" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
        {(Object.keys(byKind) as AgentKind[]).map((k) => (
          <KindCard key={k} kind={k} count={byKind[k]} total={agents.length} />
        ))}
      </div>

      <section className="card p-5">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-base font-semibold">Agent gần đây</h2>
            <div className="text-xs text-muted">Sắp xếp theo lần cập nhật mới nhất</div>
          </div>
          <Link className="btn btn-ghost text-xs" href="/agents">Xem tất cả →</Link>
        </div>
        {agents.length === 0 ? (
          <div className="text-sm text-muted py-8 text-center">
            Chưa có agent nào. <Link href="/agents/new" className="text-accent2">Tạo mới</Link>
          </div>
        ) : (
          <div className="overflow-x-auto -mx-1">
            <table className="table">
              <thead>
                <tr>
                  <th>Tên</th>
                  <th>Loại</th>
                  <th>Host</th>
                  <th>Trạng thái</th>
                  <th>Phiên bản</th>
                </tr>
              </thead>
              <tbody>
                {agents.slice(0, 8).map((a) => (
                  <tr key={a.id}>
                    <td>
                      <Link className="font-medium hover:text-accent2 transition" href={`/agents/${a.id}`}>
                        {a.displayName || a.name}
                      </Link>
                      {a.displayName && a.displayName !== a.name && (
                        <div className="text-[10px] font-mono text-muted">{a.name}</div>
                      )}
                    </td>
                    <td><span className="chip-accent">{AGENT_LABEL[a.kind as AgentKind]}</span></td>
                    <td className="text-xs">
                      <div>{a.host.name}</div>
                      <div className="font-mono text-muted text-[10px]">{a.host.host}</div>
                    </td>
                    <td><StatusChip status={a.status} /></td>
                    <td className="font-mono text-[11px] text-muted">{a.version || "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <section className="card p-5">
        <h2 className="text-base font-semibold mb-4">Hoạt động gần đây</h2>
        {events.length === 0 ? (
          <div className="text-sm text-muted py-6 text-center">Chưa có hoạt động.</div>
        ) : (
          <ul className="space-y-2">
            {events.map((e) => (
              <li key={e.id} className="flex items-start gap-3 text-sm py-1.5 border-b border-border/40 last:border-0">
                <span className={e.status === "ok" ? "chip-ok" : "chip-bad"}>{e.kind}</span>
                <Link className="text-ink hover:text-accent2 font-medium" href={`/agents/${e.agentId}`}>
                  {e.agent.displayName || e.agent.name}
                </Link>
                <span className="text-muted flex-1 truncate">{e.message}</span>
                <span className="text-muted text-[11px] font-mono whitespace-nowrap">
                  {new Date(e.createdAt).toLocaleString("vi-VN", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" })}
                </span>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}

function StatCard({
  label,
  value,
  hint,
  accent,
  pulse,
}: {
  label: string;
  value: number;
  hint?: string;
  accent?: "ok" | "bad" | "warn" | "muted" | "violet" | "cyan";
  pulse?: boolean;
}) {
  const accentMap = {
    ok: "text-ok",
    bad: "text-bad",
    warn: "text-warn",
    muted: "text-muted",
    violet: "text-[#b8a5ff]",
    cyan: "text-accent2",
  } as const;
  const dotMap: Record<string, string> = {
    ok: "dot-ok",
    bad: "dot-bad",
    warn: "dot-warn",
  };
  return (
    <div className="card p-4 relative overflow-hidden">
      <div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-muted">
        {accent && dotMap[accent] && pulse && <span className={`${dotMap[accent]} animate-pulse`} />}
        {label}
      </div>
      <div className={`text-3xl font-semibold mt-2 tracking-tight ${accent ? accentMap[accent] : "text-ink"}`}>
        {value}
      </div>
      {hint && <div className="text-[11px] text-muted mt-1">{hint}</div>}
    </div>
  );
}

function KindCard({ kind, count, total }: { kind: AgentKind; count: number; total: number }) {
  const pct = total ? Math.round((count / total) * 100) : 0;
  const grad: Record<AgentKind, string> = {
    opencode: "from-violet-500 to-fuchsia-400",
    openclaw: "from-cyan-400 to-blue-500",
    hermes: "from-amber-400 to-orange-500",
  };
  return (
    <div className="card p-4">
      <div className="flex items-center justify-between mb-2">
        <div>
          <div className="text-[11px] uppercase tracking-wider text-muted">Phân loại</div>
          <div className="text-base font-semibold">{AGENT_LABEL[kind]}</div>
        </div>
        <div className="text-2xl font-semibold font-mono">{count}</div>
      </div>
      <div className="h-1.5 rounded-full bg-white/5 overflow-hidden">
        <div
          className={`h-full bg-gradient-to-r ${grad[kind]}`}
          style={{ width: `${pct}%` }}
        />
      </div>
      <div className="text-[10px] text-muted mt-1.5 font-mono">{pct}% tổng số agent</div>
    </div>
  );
}

function StatusChip({ status }: { status: string }) {
  if (status === "running") return <span className="chip-ok"><span className="dot-ok animate-pulse" /> running</span>;
  if (status === "error") return <span className="chip-bad">{status}</span>;
  if (status === "stopped") return <span className="chip">{status}</span>;
  if (status === "installing" || status === "updating") return <span className="chip-warn">{status}</span>;
  return <span className="chip">{status}</span>;
}
