"use client";

import { useEffect, useState } from "react";

type Summary = {
  path: string;
  avgMs: number;
  p95Ms: number;
  samples: number;
  latest: string;
};

export function PerfDashboard() {
  const [data, setData] = useState<{ summary: Summary[] } | null>(null);

  async function refresh() {
    const res = await fetch("/api/admin/perf");
    if (res.ok) setData(await res.json());
  }
  useEffect(() => {
    const frame = requestAnimationFrame(() => {
      void refresh();
    });
    return () => cancelAnimationFrame(frame);
  }, []);

  async function flush() {
    await fetch("/api/admin/perf", { method: "POST" });
    await refresh();
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <button
          type="button"
          onClick={flush}
          className="rounded bg-primary px-4 py-2 text-sm font-bold text-primary-foreground"
        >
          🔄 Flush in-memory samples
        </button>
      </div>
      <div className="overflow-x-auto rounded-2xl border border-border bg-white">
        <table className="w-full text-sm">
          <thead className="border-b border-border text-left text-xs uppercase tracking-wider text-muted-foreground">
            <tr>
              <th className="px-4 py-2">Ruta</th>
              <th className="px-4 py-2">Avg (ms)</th>
              <th className="px-4 py-2">P95 (ms)</th>
              <th className="px-4 py-2">Sample-ovi</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {(data?.summary ?? []).map((s) => (
              <tr key={s.path}>
                <td className="px-4 py-2 font-mono text-xs">{s.path}</td>
                <td className="px-4 py-2 font-semibold">{s.avgMs}</td>
                <td
                  className={`px-4 py-2 font-bold ${
                    s.p95Ms > 3000 ? "text-rose-700" : s.p95Ms > 1500 ? "text-amber-700" : "text-emerald-700"
                  }`}
                >
                  {s.p95Ms}
                </td>
                <td className="px-4 py-2 text-muted-foreground">{s.samples}</td>
              </tr>
            ))}
            {(data?.summary ?? []).length === 0 && (
              <tr>
                <td colSpan={4} className="px-4 py-6 text-center text-sm text-muted-foreground">
                  Još nema sample-ova. Posetioci koji otvore portal trigeriraju beacon-e.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
