"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";

type Row = {
  id: string;
  name: string;
  displayName: string | null;
  kind: string;
  hostName: string;
  hostAddr: string;
  deployMethod: string;
  declared: boolean;
  status: string;
  version: string | null;
  uptimeSec: number | null;
  restartCount: number | null;
  updatedAt: string;
};

export default function AgentsListClient({ initialRows }: { initialRows: Row[] }) {
  const router = useRouter();
  const [rows, setRows] = useState(initialRows);
  const [busy, setBusy] = useState(false);
  const [progress, setProgress] = useState<{ done: number; total: number; current?: string } | null>(null);

  async function checkAll() {
    if (busy) return;
    setBusy(true);
    setProgress({ done: 0, total: rows.length });
    const updated = [...rows];
    for (let i = 0; i < updated.length; i++) {
      setProgress({ done: i, total: updated.length, current: updated[i].name });
      try {
        await fetch(`/api/agents/${updated[i].id}/action`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ action: "status" }),
        });
        const g = await fetch(`/api/agents/${updated[i].id}`);
        if (g.ok) {
          const j = await g.json();
          const a = j.agent;
          updated[i] = {
            ...updated[i],
            status: a.status,
            version: a.version,
            uptimeSec: a.uptimeSec ?? null,
            restartCount: a.restartCount ?? null,
            updatedAt: a.updatedAt,
          };
          setRows([...updated]);
        }
      } catch { /* skip */ }
    }
    setProgress({ done: updated.length, total: updated.length });
    setBusy(false);
    setTimeout(() => setProgress(null), 1500);
    router.refresh();
  }

  return (
    <div className="space-y-5">
      <header className="flex items-end justify-between flex-wrap gap-3">
        <div>
          <div className="text-[11px] uppercase tracking-[0.18em] text-muted mb-1">Quản lý</div>
          <h1 className="text-2xl font-semibold tracking-tight">Agents</h1>
          <div className="text-sm text-muted mt-1">{rows.length} agent · {rows.filter(r => r.status === "running").length} đang chạy</div>
        </div>
        <div className="flex gap-2">
          <button className="btn" onClick={checkAll} disabled={busy || rows.length === 0}>
            {busy && progress
              ? `Đang kiểm tra ${progress.done}/${progress.total}${progress.current ? ` · ${progress.current}` : ""}`
              : "↻ Kiểm tra tất cả"}
          </button>
          <Link href="/agents/new" className="btn btn-primary">+ Tạo agent mới</Link>
        </div>
      </header>

      {rows.length === 0 ? (
        <div className="card p-12 text-center">
          <div className="text-muted mb-3">Chưa có agent nào.</div>
          <Link href="/agents/new" className="btn btn-primary">+ Tạo agent đầu tiên</Link>
        </div>
      ) : (
        <div className="card overflow-x-auto">
          <table className="table">
            <thead>
              <tr>
                <th>Tên</th>
                <th>Loại</th>
                <th>Host</th>
                <th>Deploy</th>
                <th>Trạng thái</th>
                <th>Phiên bản</th>
                <th>Uptime</th>
                <th>Restart</th>
                <th>Cập nhật</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((a) => (
                <tr key={a.id}>
                  <td>
                    <Link href={`/agents/${a.id}`} className="font-medium hover:text-accent2 transition">
                      {a.displayName || a.name}
                    </Link>
                    {a.displayName && a.displayName !== a.name && (
                      <div className="text-[10px] text-muted font-mono">{a.name}</div>
                    )}
                  </td>
                  <td><span className="chip-accent">{a.kind}</span></td>
                  <td className="text-xs">
                    <div>{a.hostName}</div>
                    <div className="font-mono text-muted text-[10px]">{a.hostAddr}</div>
                  </td>
                  <td className="text-xs">
                    <span className="chip">{a.deployMethod}{a.declared ? " · scan" : ""}</span>
                  </td>
                  <td><StatusChip status={a.status} /></td>
                  <td className="font-mono text-[11px] text-muted">{a.version || "-"}</td>
                  <td className="font-mono text-[11px]">{fmtUptime(a.uptimeSec)}</td>
                  <td className="font-mono text-[11px]">{a.restartCount ?? "-"}</td>
                  <td className="text-[10px] text-muted font-mono">
                    {new Date(a.updatedAt).toLocaleString("vi-VN", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" })}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </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 === "installing" || status === "updating") return <span className="chip-warn">{status}</span>;
  return <span className="chip">{status}</span>;
}

function fmtUptime(sec: number | null): string {
  if (sec == null || sec < 0) return "-";
  const d = Math.floor(sec / 86400);
  const h = Math.floor((sec % 86400) / 3600);
  const m = Math.floor((sec % 3600) / 60);
  if (d > 0) return `${d}d ${h}h`;
  if (h > 0) return `${h}h ${m}m`;
  if (m > 0) return `${m}m`;
  return `${sec}s`;
}
