"use client";

import { useMemo, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { Download, Trash2 } from "lucide-react";
import {
  formatValue,
  MOMENT_LABELS,
  STATUS_STYLE,
  statusFor,
  type Moment,
} from "@/lib/glycemia";

type ReadingRow = {
  id: number;
  measuredAt: string;
  moment: string;
  value: number;
  notes: string | null;
};

type Filter = "all" | "FASTING" | "LUNCH" | "DINNER" | "out-of-range";

export function HistoryClient({ readings, isPremium }: { readings: ReadingRow[]; isPremium?: boolean }) {
  const router = useRouter();
  const [filter, setFilter] = useState<Filter>("all");
  const [pending, startTransition] = useTransition();
  const [deletingId, setDeletingId] = useState<number | null>(null);

  const filtered = useMemo(() => {
    return readings.filter((r) => {
      if (filter === "all") return true;
      if (filter === "out-of-range") {
        return statusFor(r.value, r.moment as Moment) !== "in-range";
      }
      return r.moment === filter;
    });
  }, [readings, filter]);

  async function handleDelete(id: number) {
    if (!confirm("Supprimer ce relevé ?")) return;
    setDeletingId(id);
    try {
      const res = await fetch(`/api/readings/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Suppression impossible");
      startTransition(() => router.refresh());
    } catch (e) {
      alert(e instanceof Error ? e.message : "Erreur");
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <div className="space-y-5">
      {!isPremium && (
        <div className="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
          Seuls les 7 derniers jours sont affichés sur le plan gratuit.{" "}
          <Link href="/pricing" className="font-semibold underline">Passer à Premium</Link> pour l&apos;historique complet.
        </div>
      )}
      <div className="flex flex-wrap items-end justify-between gap-3">
        <div>
          <h1 className="text-2xl font-semibold text-slate-900">Historique</h1>
          <p className="text-sm text-slate-500">
            {readings.length} relevé{readings.length > 1 ? "s" : ""} enregistré
            {readings.length > 1 ? "s" : ""}.
          </p>
        </div>
        <a
          href="/api/export"
          className="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
        >
          <Download className="h-4 w-4" />
          Exporter en CSV
        </a>
      </div>

      <div className="flex flex-wrap gap-2">
        <FilterPill active={filter === "all"} onClick={() => setFilter("all")}>
          Tous
        </FilterPill>
        <FilterPill active={filter === "FASTING"} onClick={() => setFilter("FASTING")}>
          Matin
        </FilterPill>
        <FilterPill active={filter === "LUNCH"} onClick={() => setFilter("LUNCH")}>
          Midi
        </FilterPill>
        <FilterPill active={filter === "DINNER"} onClick={() => setFilter("DINNER")}>
          Soir
        </FilterPill>
        <FilterPill active={filter === "out-of-range"} onClick={() => setFilter("out-of-range")}>
          Hors cible
        </FilterPill>
      </div>

      <div className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
        {filtered.length === 0 ? (
          <div className="px-4 py-10 text-center text-sm text-slate-500">
            Aucun relevé pour ce filtre.
          </div>
        ) : (
          <ul className="divide-y divide-slate-100">
            {filtered.map((r) => {
              const status = statusFor(r.value, r.moment as Moment);
              const date = new Date(r.measuredAt);
              return (
                <li
                  key={r.id}
                  className="flex items-center gap-3 px-4 py-3 transition hover:bg-slate-50"
                >
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
                      <span className="text-base font-semibold text-slate-900">
                        {formatValue(r.value)}
                      </span>
                      <span
                        className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] font-medium ${STATUS_STYLE[status].bg} ${STATUS_STYLE[status].color} ${STATUS_STYLE[status].border}`}
                      >
                        {STATUS_STYLE[status].label}
                      </span>
                      <span className="text-xs text-slate-500">
                        {MOMENT_LABELS[r.moment as Moment]}
                      </span>
                    </div>
                    <div className="mt-0.5 text-xs text-slate-500">
                      {format(date, "EEEE d MMM yyyy 'à' HH:mm", { locale: fr })}
                    </div>
                    {r.notes && (
                      <div className="mt-1 text-sm text-slate-600 italic line-clamp-2">
                        « {r.notes} »
                      </div>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => handleDelete(r.id)}
                    disabled={pending && deletingId === r.id}
                    className="rounded-md p-2 text-slate-400 hover:bg-rose-50 hover:text-rose-600 disabled:opacity-50"
                    aria-label="Supprimer"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </div>
  );
}

function FilterPill({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`rounded-full border px-3 py-1.5 text-xs font-medium transition ${
        active
          ? "border-teal-600 bg-teal-600 text-white"
          : "border-slate-300 bg-white text-slate-700 hover:bg-slate-50"
      }`}
    >
      {children}
    </button>
  );
}
