/**
 * Trouve-KA — dashboard admin (vue d'ensemble + contrôles + flux live)
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 */

"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Controls } from "@/components/admin/controls";
import { HttpBars } from "@/components/admin/http-bars";
import { LiveFeed } from "@/components/admin/live-feed";
import { RecentErrors } from "@/components/admin/recent-errors";
import { TopDomains } from "@/components/admin/top-domains";
import { Stat } from "@/components/stat";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { adminFetch, UnauthorizedError } from "@/lib/admin";
import { formatNumber } from "@/lib/format";
import type { AdminOverview } from "@/lib/types";

const REFRESH_MS = 10_000;

interface AdminDashboardProps {
  token: string;
  onUnauthorized: () => void;
  onLogout: () => void;
}

export function AdminDashboard({
  token,
  onUnauthorized,
  onLogout,
}: AdminDashboardProps) {
  const [overview, setOverview] = useState<AdminOverview | null>(null);
  const [error, setError] = useState(false);

  const refresh = useCallback(async () => {
    try {
      const data = await adminFetch<AdminOverview>(
        "/api/admin/overview",
        token,
      );
      setOverview(data);
      setError(false);
    } catch (err) {
      if (err instanceof UnauthorizedError) {
        onUnauthorized();
        return;
      }
      setError(true);
    }
  }, [token, onUnauthorized]);

  useEffect(() => {
    refresh();
    const id = setInterval(refresh, REFRESH_MS);
    return () => clearInterval(id);
  }, [refresh]);

  return (
    <div className="flex-1">
      <div className="border-b-[1.5px] border-ink bg-surface-2">
        <div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-3.5">
          <div className="flex items-center gap-3">
            <Link
              href="/"
              className="klabel rounded-sm transition-colors hover:text-ink"
            >
              Trouve-KA
            </Link>
            <span className="text-sm text-ink-3">/</span>
            <h1 className="font-display text-sm font-bold tracking-[-0.02em] text-ink">
              Administration
            </h1>
            {overview ? (
              overview.paused ? (
                <Badge variant="warning">En pause</Badge>
              ) : (
                <span className="stat-chip px-3 py-1 text-[11px]">
                  <span className="pulse-dot" aria-hidden="true" />
                  En marche
                </span>
              )
            ) : null}
          </div>
          <Button variant="ghost" size="sm" onClick={onLogout}>
            Se déconnecter
          </Button>
        </div>
      </div>

      <main id="contenu" className="mx-auto max-w-6xl space-y-7 px-4 py-6">
        {error && !overview ? (
          <p className="rounded-ctl border-[1.5px] border-ink bg-danger-soft px-4 py-3 text-sm font-medium text-danger shadow-off-field">
            Impossible de joindre l'API d'administration. Vérifiez que le
            backend tourne, puis rechargez la page.
          </p>
        ) : null}

        {overview ? (
          <>
            <section aria-labelledby="titre-frontier">
              <h2 id="titre-frontier" className="kicker">
                Frontier
              </h2>
              <div className="mt-3 grid grid-cols-2 gap-3 sm:grid-cols-5">
                <Stat
                  label="En attente"
                  value={formatNumber(overview.frontier.pending)}
                />
                <Stat
                  label="En cours"
                  value={formatNumber(overview.frontier.in_progress)}
                />
                <Stat
                  label="Complétées"
                  value={formatNumber(overview.frontier.done)}
                />
                <Stat
                  label="Échouées"
                  value={formatNumber(overview.frontier.failed)}
                />
                <Stat
                  label="Bloquées"
                  value={formatNumber(overview.frontier.blocked)}
                />
              </div>
            </section>

            <section aria-labelledby="titre-debits">
              <h2 id="titre-debits" className="kicker">
                Débits (dernière heure)
              </h2>
              <div className="mt-3 grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-8">
                <Stat
                  label="Téléchargées"
                  value={formatNumber(overview.rates.fetched_1h)}
                />
                <Stat
                  label="Analysées"
                  value={formatNumber(overview.rates.parsed_1h)}
                />
                <Stat
                  label="Indexées"
                  value={formatNumber(overview.rates.indexed_1h)}
                />
                <Stat
                  label="Erreurs"
                  value={formatNumber(overview.rates.errors_1h)}
                />
                <Stat
                  label="Refus robots"
                  value={formatNumber(overview.rates.robots_blocked_1h)}
                />
                <Stat
                  label="Doublons"
                  value={formatNumber(overview.rates.duplicates_1h)}
                />
                <Stat
                  label="Latence fetch p50"
                  value={`${formatNumber(overview.latency.fetch_p50_ms)} ms`}
                />
                <Stat
                  label="Latence fetch p95"
                  value={`${formatNumber(overview.latency.fetch_p95_ms)} ms`}
                />
              </div>
            </section>

            <div className="grid gap-6 lg:grid-cols-2">
              <HttpBars data={overview.http_status} />
              <TopDomains domains={overview.top_domains} />
            </div>

            <div className="grid items-start gap-6 lg:grid-cols-2">
              <Controls
                token={token}
                paused={overview.paused}
                onUnauthorized={onUnauthorized}
                onRefresh={refresh}
              />
              <RecentErrors errors={overview.recent_errors} />
            </div>

            <LiveFeed token={token} onUnauthorized={onUnauthorized} />
          </>
        ) : !error ? (
          <div aria-hidden="true" className="grid animate-pulse gap-3 sm:grid-cols-4">
            {Array.from({ length: 8 }, (_, i) => (
              <div key={i} className="h-24 rounded-card bg-line" />
            ))}
          </div>
        ) : null}
      </main>
    </div>
  );
}
