/**
 * Trouve-KA — flux live du crawl (poll toutes les 3 s)
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 */

"use client";

import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  adminFetch,
  UnauthorizedError,
} from "@/lib/admin";
import { formatTime } from "@/lib/format";
import type { AdminRecentResponse, CrawlEvent } from "@/lib/types";

const POLL_MS = 3_000;

function outcomeBadge(outcome: string) {
  switch (outcome) {
    case "indexed":
      return <Badge variant="success">Indexée</Badge>;
    case "duplicate":
      return <Badge>Doublon</Badge>;
    case "error":
      return <Badge variant="danger">Erreur</Badge>;
    case "not_quebec":
      return <Badge>Hors Québec</Badge>;
    case "robots_blocked":
      return <Badge variant="warning">Robots</Badge>;
    default:
      return <Badge>{outcome}</Badge>;
  }
}

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

export function LiveFeed({ token, onUnauthorized }: LiveFeedProps) {
  const [events, setEvents] = useState<CrawlEvent[] | null>(null);
  const [stalled, setStalled] = useState(false);

  useEffect(() => {
    let active = true;

    async function load() {
      try {
        const data = await adminFetch<AdminRecentResponse>(
          "/api/admin/recent?limit=50",
          token,
        );
        if (!active) return;
        setEvents(data.events);
        setStalled(false);
      } catch (err) {
        if (!active) return;
        if (err instanceof UnauthorizedError) {
          onUnauthorized();
          return;
        }
        setStalled(true);
      }
    }

    load();
    const id = setInterval(load, POLL_MS);
    return () => {
      active = false;
      clearInterval(id);
    };
  }, [token, onUnauthorized]);

  return (
    <Card>
      <CardHeader className="flex items-baseline justify-between gap-2">
        <CardTitle>Flux live du crawl</CardTitle>
        <span className="klabel">
          {stalled ? "Flux interrompu — reconnexion…" : "Actualisé toutes les 3 s"}
        </span>
      </CardHeader>
      <CardContent>
        {events === null ? (
          <p className="text-sm text-ink-2">Chargement du flux…</p>
        ) : events.length === 0 ? (
          <p className="text-sm text-ink-2">
            Aucun événement récent. Le robot est peut-être en pause.
          </p>
        ) : (
          <ul
            aria-label="Événements récents du robot"
            className="max-h-96 divide-y divide-line overflow-y-auto"
          >
            {events.map((event, index) => (
              <li
                key={`${event.at}-${event.url}-${index}`}
                className="flex items-center gap-3 py-2 text-sm"
              >
                <span className="gk-mono shrink-0 tabular-nums text-xs text-ink-3">
                  {formatTime(event.at)}
                </span>
                <span className="shrink-0">{outcomeBadge(event.outcome)}</span>
                <span className="gk-mono shrink-0 tabular-nums text-xs text-ink-2">
                  {event.status || "—"}
                </span>
                <span className="min-w-0 flex-1 truncate text-ink">
                  {event.title || event.url}
                </span>
                {typeof event.quebec_score === "number" ? (
                  <span className="gk-mono shrink-0 tabular-nums text-xs text-ink-2">
                    QC&nbsp;{event.quebec_score.toFixed(2)}
                  </span>
                ) : null}
              </li>
            ))}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
