import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { env } from "@/lib/env";
import { getApiMetricsSnapshot } from "@/lib/api-metrics";

type Props = {
  searchParams: Promise<{ key?: string }>;
};

export const metadata: Metadata = {
  title: "Admin API Metrics",
  robots: { index: false, follow: false },
};

function formatTimestamp(value: number | null) {
  if (!value) {
    return "Aucune";
  }

  return new Date(value).toLocaleString("fr-FR");
}

function formatDurationMs(value: number) {
  if (value % 1000 === 0) {
    return `${value / 1000}s`;
  }

  return `${value}ms`;
}

export default async function AdminApiMetricsPage({ searchParams }: Props) {
  const { key } = await searchParams;

  if (!env.seoAdminKey) {
    return (
      <section className="space-y-3 rounded-2xl border border-[#ffdede] bg-white p-6">
        <h1 className="font-serif text-3xl text-[var(--foreground)]">Admin API Metrics</h1>
        <p className="text-sm text-[var(--muted)]">Definis la variable d&apos;environnement <code>SEO_ADMIN_KEY</code> pour proteger cette page.</p>
      </section>
    );
  }

  if (key !== env.seoAdminKey) {
    notFound();
  }

  const snapshot = getApiMetricsSnapshot();
  const cards = [
    {
      id: "suggestions",
      title: "Autocomplete",
      path: "/api/search/suggestions",
      data: snapshot.metrics.searchSuggestions,
    },
    {
      id: "search-page",
      title: "Page recherche",
      path: "/recherche",
      data: snapshot.metrics.searchPage,
    },
  ];

  return (
    <div className="space-y-6">
      <header className="rounded-[1.5rem] border border-[#ffdede] bg-white p-6">
        <p className="text-xs font-semibold uppercase tracking-[0.14em] text-[var(--accent-3)]">Admin</p>
        <h1 className="mt-1 font-serif text-4xl text-[var(--foreground)]">API Metrics</h1>
        <p className="mt-2 text-sm text-[var(--muted)]">
          Compteurs en memoire du process Next.js pour surveiller les routes qui peuvent consommer Sanity.
        </p>
        <p className="mt-2 text-xs text-[var(--muted)]">Snapshot genere le {formatTimestamp(snapshot.generatedAt)}.</p>
      </header>

      <section className="grid gap-4 xl:grid-cols-2">
        {cards.map((card) => (
          <article key={card.id} className="space-y-4 rounded-[1.25rem] border border-[var(--line)] bg-white p-5">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.14em] text-[var(--accent-3)]">{card.title}</p>
              <h2 className="mt-1 text-lg font-semibold text-[var(--foreground)]">{card.path}</h2>
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              <div className="rounded-xl border border-[var(--line)] bg-[#fffafa] p-4">
                <p className="text-xs text-[var(--muted)]">Requetes autorisees</p>
                <p className="mt-1 text-2xl font-semibold text-[var(--foreground)]">{card.data.allowed}</p>
              </div>
              <div className="rounded-xl border border-[var(--line)] bg-[#fff5f5] p-4">
                <p className="text-xs text-[var(--muted)]">Requetes bloquees</p>
                <p className="mt-1 text-2xl font-semibold text-[var(--foreground)]">{card.data.blocked}</p>
              </div>
              <div className="rounded-xl border border-[var(--line)] bg-white p-4">
                <p className="text-xs text-[var(--muted)]">Clients suivis en memoire</p>
                <p className="mt-1 text-2xl font-semibold text-[var(--foreground)]">{card.data.activeClients}</p>
              </div>
              <div className="rounded-xl border border-[var(--line)] bg-white p-4">
                <p className="text-xs text-[var(--muted)]">Rate limit</p>
                <p className="mt-1 text-sm font-semibold text-[var(--foreground)]">
                  {card.data.maxRequests} req / {formatDurationMs(card.data.windowMs)}
                </p>
              </div>
            </div>

            <div className="overflow-hidden rounded-xl border border-[var(--line)]">
              <table className="min-w-full text-sm">
                <tbody>
                  <tr className="border-b border-[var(--line)]">
                    <td className="px-4 py-3 text-[var(--muted)]">Derniere requete autorisee</td>
                    <td className="px-4 py-3 text-[var(--foreground)]">{formatTimestamp(card.data.lastAllowedAt)}</td>
                  </tr>
                  <tr className="border-b border-[var(--line)]">
                    <td className="px-4 py-3 text-[var(--muted)]">Derniere query autorisee</td>
                    <td className="px-4 py-3 text-[var(--foreground)]">{card.data.lastAllowedQuery || "Aucune"}</td>
                  </tr>
                  <tr className="border-b border-[var(--line)]">
                    <td className="px-4 py-3 text-[var(--muted)]">Derniere requete bloquee</td>
                    <td className="px-4 py-3 text-[var(--foreground)]">{formatTimestamp(card.data.lastBlockedAt)}</td>
                  </tr>
                  <tr>
                    <td className="px-4 py-3 text-[var(--muted)]">Derniere query bloquee</td>
                    <td className="px-4 py-3 text-[var(--foreground)]">{card.data.lastBlockedQuery || "Aucune"}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </article>
        ))}
      </section>

      <section className="rounded-[1.25rem] border border-[var(--line)] bg-white p-5">
        <h2 className="text-lg font-semibold text-[var(--foreground)]">Sanity public reads</h2>
        <p className="mt-2 text-sm text-[var(--muted)]">
          La prod est configuree pour lire le contenu public via le CDN Sanity avec la perspective <code>published</code>.
          Ces compteurs suivent surtout la recherche autocomplete et la page <code>/recherche</code>, qui sont les points les plus sensibles pour ton quota.
        </p>
      </section>
    </div>
  );
}
