import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { PageShell } from "@/components/page-shell";
import { ensureAnonymousSession } from "@/lib/ensure-session";

type Analytics = {
  totalRequests: number; totalCost: number; avgLatency: number;
  byTool: Record<string, { total: number; success: number; error: number; cost: number; avgLatency: number }>;
  recent: Array<{ tool: string; status: string; latency_ms: number | null; estimated_cost_usd: number | null; created_at: string }>;
};

export const Route = createFileRoute("/admin")({
  head: () => ({ meta: [{ title: "Admin — Gatavase AI Creative" }, { name: "robots", content: "noindex" }] }),
  component: AdminPage,
});

function AdminPage() {
  const [data, setData] = useState<Analytics | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => { void load(); }, []);
  async function load() {
    await ensureAnonymousSession();
    try {
      const { getAdminAnalytics } = await import("@/lib/history.functions");
      setData(await getAdminAnalytics());
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load");
    }
  }

  return (
    <PageShell eyebrow="Admin" title="Usage analytics" lead="Requests, success rates, latency and cost across all Gatavase AI tools (last 30 days).">
      <div className="mb-4"><Link to="/studio" className="text-sm text-primary underline">← Back to Studio</Link></div>
      {error && (
        <div className="glow-card rounded-2xl p-6">
          <div className="text-sm text-destructive">{error}</div>
          <p className="mt-2 text-xs text-muted-foreground">
            Admin access is granted by inserting a row into <code>user_roles</code> with role <code>admin</code>.
          </p>
        </div>
      )}
      {!data && !error && <div className="text-sm text-muted-foreground">Loading…</div>}
      {data && (
        <>
          <div className="mb-6 grid gap-4 sm:grid-cols-3">
            <Stat label="Total requests (30d)" value={data.totalRequests.toLocaleString()} />
            <Stat label="Estimated cost" value={`$${data.totalCost.toFixed(2)}`} />
            <Stat label="Avg latency" value={`${data.avgLatency} ms`} />
          </div>

          <div className="glow-card mb-6 overflow-x-auto rounded-2xl">
            <table className="w-full text-sm">
              <thead className="bg-background/40 text-xs uppercase tracking-wider text-muted-foreground">
                <tr><th className="p-3 text-left">Tool</th><th className="p-3">Requests</th><th className="p-3">Success</th><th className="p-3">Errors</th><th className="p-3">Success rate</th><th className="p-3">Avg latency</th><th className="p-3">Cost</th></tr>
              </thead>
              <tbody>
                {Object.entries(data.byTool).sort((a,b) => b[1].total - a[1].total).map(([tool, s]) => (
                  <tr key={tool} className="border-t border-border/40">
                    <td className="p-3 font-medium">{tool}</td>
                    <td className="p-3 text-center">{s.total}</td>
                    <td className="p-3 text-center text-emerald-400">{s.success}</td>
                    <td className="p-3 text-center text-destructive">{s.error}</td>
                    <td className="p-3 text-center">{s.total ? Math.round((s.success / s.total) * 100) : 0}%</td>
                    <td className="p-3 text-center">{s.avgLatency} ms</td>
                    <td className="p-3 text-center">${s.cost.toFixed(3)}</td>
                  </tr>
                ))}
                {Object.keys(data.byTool).length === 0 && (
                  <tr><td colSpan={7} className="p-6 text-center text-muted-foreground">No usage yet.</td></tr>
                )}
              </tbody>
            </table>
          </div>

          <div className="glow-card rounded-2xl p-5">
            <h3 className="mb-3 font-display font-semibold">Recent activity</h3>
            <div className="space-y-1 text-xs font-mono">
              {data.recent.map((r, i) => (
                <div key={i} className="flex justify-between border-b border-border/30 py-1">
                  <span>{new Date(r.created_at).toLocaleString()}</span>
                  <span>{r.tool}</span>
                  <span className={r.status === "success" ? "text-emerald-400" : "text-destructive"}>{r.status}</span>
                  <span>{r.latency_ms ?? 0} ms</span>
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </PageShell>
  );
}

function Stat({ label, value }: { label: string; value: string }) {
  return (
    <div className="glow-card rounded-2xl p-5">
      <div className="text-xs uppercase tracking-widest text-muted-foreground">{label}</div>
      <div className="mt-2 font-display text-2xl font-bold">{value}</div>
    </div>
  );
}
