/**
 * Trouve-KA — panneau client d'état du moteur (auto-refresh 10 s)
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 */

"use client";

import { useEffect, useState } from "react";
import { Stat } from "@/components/stat";
import { Badge } from "@/components/ui/badge";
import { formatNumber } from "@/lib/format";
import type { StatusResponse } from "@/lib/types";

const REFRESH_MS = 10_000;

function crawlerBadge(state: string) {
  if (state === "running") {
    return (
      <span className="stat-chip">
        <span className="pulse-dot" aria-hidden="true" />
        Robot en marche
      </span>
    );
  }
  if (state === "paused") {
    return <Badge variant="warning">Robot en pause</Badge>;
  }
  return <Badge>Robot&nbsp;: {state || "état inconnu"}</Badge>;
}

export function StatusPanel() {
  const [status, setStatus] = useState<StatusResponse | null>(null);
  const [error, setError] = useState(false);
  const [updatedAt, setUpdatedAt] = useState<string>("");

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

    async function load() {
      try {
        const res = await fetch("/api/status");
        if (!res.ok) throw new Error(`Erreur ${res.status}`);
        const data = (await res.json()) as StatusResponse;
        if (!active) return;
        setStatus(data);
        setError(false);
        setUpdatedAt(
          new Intl.DateTimeFormat("fr-CA", {
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
          }).format(new Date()),
        );
      } catch {
        if (active) setError(true);
      }
    }

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

  if (error && !status) {
    return (
      <p className="mt-8 text-ink-2">
        Impossible de joindre le moteur pour le moment. Réessayez sous peu.
      </p>
    );
  }

  if (!status) {
    return (
      <div aria-hidden="true" className="mt-8 grid animate-pulse gap-4 sm:grid-cols-3">
        {Array.from({ length: 6 }, (_, i) => (
          <div key={i} className="h-24 rounded-card bg-line" />
        ))}
      </div>
    );
  }

  return (
    <div className="mt-8">
      {/* Chiffre-vedette : la taille de l'index. */}
      <div className="gk-card p-6">
        <p className="klabel">Pages indexées</p>
        <p className="mt-2 font-display text-5xl font-bold tracking-[-0.03em] text-ink sm:text-6xl">
          {formatNumber(status.pages_indexed)}
        </p>
        <div className="mt-5 flex flex-wrap items-center gap-2.5">
          {crawlerBadge(status.crawler_state)}
          {status.search_ok ? (
            <Badge variant="success">Recherche opérationnelle</Badge>
          ) : (
            <Badge variant="danger">Recherche dégradée</Badge>
          )}
        </div>
      </div>

      <div className="mt-5 grid gap-4 sm:grid-cols-3">
        <Stat
          label="Domaines connus"
          value={formatNumber(status.domains_count)}
        />
        <Stat
          label="Pages indexées (dernière heure)"
          value={formatNumber(status.indexed_last_hour)}
        />
        <Stat
          label="Pages téléchargées (dernière heure)"
          value={formatNumber(status.fetched_last_hour)}
        />
        <Stat
          label="URL en attente de crawl"
          value={formatNumber(status.frontier_pending)}
        />
        <Stat
          label="URL en cours de crawl"
          value={formatNumber(status.frontier_in_progress)}
        />
        <Stat
          label="Erreurs (dernière heure)"
          value={formatNumber(status.errors_last_hour)}
        />
      </div>

      <p className="gk-mono mt-5 text-[11px] text-ink-3" aria-live="polite">
        {error
          ? "Mise à jour interrompue — nouvelles tentatives en cours."
          : updatedAt
            ? `Dernière mise à jour à ${updatedAt}.`
            : ""}
      </p>
    </div>
  );
}
