"use client";

import { useEffect, useState } from "react";
import { Bot, RefreshCw, Loader2, AlertCircle } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { fr } from "date-fns/locale";

type State =
  | { status: "loading" }
  | { status: "ok"; content: string; generatedAt: Date; fresh: boolean; warning?: string }
  | { status: "error"; message: string };

export function DailyInsight() {
  const [state, setState] = useState<State>({ status: "loading" });
  const [refreshing, setRefreshing] = useState(false);

  async function load(forceRefresh = false) {
    if (forceRefresh) setRefreshing(true);
    else setState({ status: "loading" });

    try {
      const url = forceRefresh ? "/api/daily-analysis?refresh=1" : "/api/daily-analysis";
      const res = await fetch(url);
      const data = await res.json();

      if (!res.ok || data.error) {
        setState({ status: "error", message: data.error ?? `Erreur ${res.status}` });
        return;
      }

      setState({
        status: "ok",
        content: data.content,
        generatedAt: new Date(data.generatedAt),
        fresh: data.fresh,
        warning: data.warning,
      });
    } catch (e) {
      setState({ status: "error", message: e instanceof Error ? e.message : "Erreur réseau" });
    } finally {
      setRefreshing(false);
    }
  }

  useEffect(() => { load(); }, []);

  return (
    <section className="rounded-xl border border-teal-200 bg-gradient-to-br from-teal-50 to-white p-5 shadow-sm">
      <div className="mb-3 flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <div className="flex h-7 w-7 items-center justify-center rounded-full bg-teal-100">
            <Bot className="h-4 w-4 text-teal-700" />
          </div>
          <h2 className="text-sm font-semibold text-teal-800">Analyse du jour — Diablo</h2>
        </div>
        <button
          type="button"
          onClick={() => load(true)}
          disabled={refreshing || state.status === "loading"}
          title="Régénérer l'analyse"
          className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-teal-700 hover:bg-teal-100 disabled:opacity-40 transition"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? "animate-spin" : ""}`} />
          Actualiser
        </button>
      </div>

      {state.status === "loading" && (
        <div className="flex items-center gap-2 text-sm text-slate-500">
          <Loader2 className="h-4 w-4 animate-spin text-teal-600" />
          Génération de l'analyse en cours…
        </div>
      )}

      {state.status === "error" && (
        <div className="flex items-start gap-2 rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-800">
          <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
          <span>{state.message}</span>
        </div>
      )}

      {state.status === "ok" && (
        <>
          {state.warning && (
            <div className="mb-2 flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
              <AlertCircle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
              Analyse précédente affichée : {state.warning}
            </div>
          )}
          <p className="text-sm leading-relaxed text-slate-700">{state.content}</p>
          <p className="mt-3 text-xs text-slate-400">
            Générée {formatDistanceToNow(state.generatedAt, { addSuffix: true, locale: fr })}
            {" · "}
            <span className="italic">Conseil informatif — consultez votre médecin</span>
          </p>
        </>
      )}
    </section>
  );
}
