import { Head, Link } from '@inertiajs/react';
import LotoLayout from '@/Layouts/LotoLayout';
import { useState } from "react";
import {
  ArrowLeft,
  Flame,
  BarChart3,
  ListOrdered,
  CalendarRange,
  Plus,
  Download,
  Upload,
  FileDown,
  Save,
} from "lucide-react";
import { router, usePage } from "@inertiajs/react";
import { motion } from "framer-motion";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import { EditDrawModal } from "@/Components/loto/EditDrawModal";
import { DeleteDrawModal } from "@/Components/loto/DeleteDrawModal";
import { DashboardHeader } from "@/Components/loto/DashboardHeader";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogTrigger,
} from "@/Components/ui/dialog";
import {
  computeStatsFromRows,
  getDrawNameBySlug,
  getDrawTime,
  type DrawStats,
  type DrawResultRow,
  type FreqEntry,
  type RankedFreq,
} from "@/lib/loto-data";

function SectionCard({
  title,
  subtitle,
  icon,
  children,
}: {
  title: string;
  subtitle?: string;
  icon: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <div className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
      <div className="flex items-center gap-3">
        <div className="flex h-9 w-9 items-center justify-center rounded-xl gradient-orange text-primary-foreground shadow-[var(--shadow-glow)]">
          {icon}
        </div>
        <div>
          <h2 className="font-display text-lg font-bold leading-tight">{title}</h2>
          {subtitle && <p className="text-xs text-muted-foreground">{subtitle}</p>}
        </div>
      </div>
      <div className="mt-4">{children}</div>
    </div>
  );
}

function RankedTable({ rank }: { rank: RankedFreq }) {
  const rows: { label: string; entry: FreqEntry; hot: boolean }[] = [
    ...rank.most.map((entry, i) => ({
      label:
        i === 0
          ? "N° LE PLUS SOUVENT SORTI"
          : `${i + 1}e N° LE PLUS SOUVENT SORTI`,
      entry,
      hot: true,
    })),
    ...rank.least.map((entry, i) => ({
      label:
        i === 0
          ? "N° LE MOINS SOUVENT SORTI"
          : `${i + 1}e N° LE MOINS SOUVENT SORTI`,
      entry,
      hot: false,
    })),
  ];

  return (
    <table className="w-full border-collapse text-sm">
      <thead>
        <tr className="text-left text-[10px] uppercase tracking-wider text-muted-foreground">
          <th className="pb-2 font-medium">Type</th>
          <th className="pb-2 text-center font-medium">N°</th>
          <th className="pb-2 text-right font-medium">Sorties</th>
        </tr>
      </thead>
      <tbody>
        {rows.map((r, i) => (
          <tr key={i} className="border-t border-border/60">
            <td className="py-2 text-xs font-medium text-foreground">{r.label}</td>
            <td className="py-2 text-center">
              <span
                className={`inline-flex h-7 w-7 items-center justify-center rounded-full text-xs font-bold tabular-nums ${
                  r.hot
                    ? "gradient-orange text-primary-foreground"
                    : "bg-muted text-muted-foreground"
                }`}
              >
                {String(r.entry.num).padStart(2, "0")}
              </span>
            </td>
            <td className="py-2 text-right font-bold tabular-nums">{r.entry.freq}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function HotList({ items }: { items: FreqEntry[] }) {
  return (
    <div className="space-y-2">
      {items.map((it, i) => (
        <div
          key={it.num}
          className="flex items-center justify-between rounded-xl bg-muted/40 px-3 py-2"
        >
          <span className="text-xs font-medium text-muted-foreground">
            {i === 0 ? "N° LE PLUS SOUVENT SORTI" : `${i + 1}e N° LE PLUS SOUVENT SORTI`}
          </span>
          <span className="flex items-center gap-2">
            <span className="inline-flex h-7 w-7 items-center justify-center rounded-full gradient-orange text-xs font-bold text-primary-foreground tabular-nums">
              {String(it.num).padStart(2, "0")}
            </span>
            <span className="w-5 text-right text-sm font-bold tabular-nums">{it.freq}</span>
          </span>
        </div>
      ))}
    </div>
  );
}

function AllNumbersGrid({ items }: { items: FreqEntry[] }) {
  return (
    <div className="grid grid-cols-4 gap-1.5 sm:grid-cols-6">
      {items.map((it) => (
        <div
          key={it.num}
          className="flex items-center justify-center gap-1 rounded-lg border border-border/60 bg-background px-1.5 py-1.5 text-xs tabular-nums"
        >
          <span className="font-bold text-foreground">{String(it.num).padStart(2, "0")}</span>
          <span className="text-muted-foreground">({it.freq})</span>
        </div>
      ))}
    </div>
  );
}

function computeHot(rows: DrawResultRow[], key: "first" | "last"): FreqEntry[] {
  const counts = new Map<number, number>();
  for (const r of rows) {
    r[key].forEach((n) => counts.set(n, (counts.get(n) ?? 0) + 1));
  }
  return [...counts.entries()]
    .map(([num, freq]) => ({ num, freq }))
    .sort((a, b) => b.freq - a.freq || a.num - b.num)
    .slice(0, 5);
}

const FR_MONTHS_INPUT = [
  "janvier", "février", "mars", "avril", "mai", "juin",
  "juillet", "août", "septembre", "octobre", "novembre", "décembre",
];

function todayFr(): string {
  const d = new Date();
  return `${d.getDate()} ${FR_MONTHS_INPUT[d.getMonth()]} ${d.getFullYear()}`;
}

export default function DrawStatsPage({ drawSlug, dbResults }: { drawSlug: string, dbResults: any[] }) {
  const name = getDrawNameBySlug(drawSlug);
  if (!name) return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <h1 className="text-4xl font-bold text-foreground">Tirage introuvable</h1>
        <p className="mt-2 text-muted-foreground">Ce tirage n'existe pas.</p>
        <Link href="/" className="mt-6 inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90">
          Retour au tableau de bord
        </Link>
      </div>
    </div>
  );
  
  const stats = computeStatsFromRows(name, dbResults);
  return <DrawStatsContent stats={stats} dbResults={dbResults} />;
}

DrawStatsPage.layout = (page: React.ReactNode) => <LotoLayout>{page}</LotoLayout>;

function DrawStatsContent({ stats, dbResults }: { stats: DrawStats, dbResults: any[] }) {
  const { auth } = usePage<any>().props;
  const isAdmin = auth?.user?.role === 'admin';
  const [results, setResults] = useState<DrawResultRow[]>(stats.results);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [date, setDate] = useState(todayFr());
  const [firstStr, setFirstStr] = useState("");
  const [lastStr, setLastStr] = useState("");
  const [error, setError] = useState("");
  const [exportOpen, setExportOpen] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [importError, setImportError] = useState("");
  const [importSummary, setImportSummary] = useState("");
  const [isSavingBulk, setIsSavingBulk] = useState(false);
  const [historySearch, setHistorySearch] = useState("");
  const [sections, setSections] = useState({
    stats: true,
    hot: true,
    all: true,
    last25: true,
    history: true,
  });

  const toggleSection = (key: keyof typeof sections) =>
    setSections((s) => ({ ...s, [key]: !s[key] }));

  const handleBulkSave = () => {
    const newDraws = results.filter((r: any) => !r.id);
    if (newDraws.length === 0) return;
    setIsSavingBulk(true);
    router.post('/draws/bulk', { draws: newDraws as any, name: stats.name }, {
      preserveScroll: true,
      onSuccess: () => {
        setIsSavingBulk(false);
        // Page will refresh and DB results will merge into state via props
      },
      onError: () => setIsSavingBulk(false)
    });
  };

  const hotFirst = computeHot(results, "first");
  const hotLast = computeHot(results, "last");

  const term = historySearch.toLowerCase().trim();
  const searchNums = term.split(/[\s,]+/).filter(x => /^\d+$/.test(x)).map(Number);

  const filteredHistory = results.filter((r) => {
    if (!historySearch) return true;
    
    // Si on cherche uniquement des numéros, on garde toutes les lignes (pour juste les surligner)
    if (/^[\d\s,]+$/.test(term)) {
      return true;
    }
    
    if (r.date.toLowerCase().includes(term)) return true;
    
    return false;
  });

  const parseNums = (s: string): number[] =>
    s
      .split(/[\s,]+/)
      .map((x) => parseInt(x, 10))
      .filter((n) => !Number.isNaN(n));

  const handleAddDraw = () => {
    const first = parseNums(firstStr);
    const last = parseNums(lastStr);
    if (first.length !== 5 || last.length !== 5) {
      setError("Veuillez saisir exactement 5 numéros pour chaque colonne.");
      return;
    }
    if ([...first, ...last].some((n) => n < 1 || n > 90)) {
      setError("Les numéros doivent être compris entre 1 et 90.");
      return;
    }
    const nextNo = results.length ? results[0].drawNo + 1 : 1;
    setResults([{ drawNo: nextNo, date: date || todayFr(), first, last }, ...results]);
    setFirstStr("");
    setLastStr("");
    setError("");
    setDialogOpen(false);
  };

  const handleUpdateLocal = (id: string, updated: any) => {
    setResults(results.map((r: any) => (r.db_id?.toString() === id || r.drawNo?.toString() === id) ? { ...r, ...updated } : r));
  };

  const handleDeleteLocal = (id: string) => {
    setResults(results.filter((r: any) => (r.db_id?.toString() !== id && r.drawNo?.toString() !== id)));
  };

  const handleDownloadSample = () => {
    const sample = [
      "date,premiers,derniers",
      "5 juin 2026,12 47 8 63 29,5 81 34 19 70",
      "29 mai 2026,3 55 71 22 40,88 16 49 7 61",
      "22 mai 2026,77 14 38 90 6,25 52 11 68 43",
    ].join("\n");
    const blob = new Blob([sample], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `modele-import-${stats.name}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleImportFile = (file: File) => {
    setImportError("");
    setImportSummary("");
    const reader = new FileReader();
    reader.onload = () => {
      const text = String(reader.result ?? "");
      const lines = text
        .split(/\r?\n/)
        .map((l) => l.trim())
        .filter(Boolean);
      if (!lines.length) {
        setImportError("Le fichier est vide.");
        return;
      }
      // Ignorer l'en-tête s'il est présent
      const dataLines = /date/i.test(lines[0]) ? lines.slice(1) : lines;
      const imported: DrawResultRow[] = [];
      let nextNo = results.length ? results[0].drawNo + 1 : 1;
      for (let i = 0; i < dataLines.length; i++) {
        const cols = dataLines[i].split(/[,;]/).map((c) => c.trim());
        if (cols.length < 3) {
          setImportError(`Ligne ${i + 1} invalide : 3 colonnes attendues (date, premiers, derniers).`);
          return;
        }
        const [dateCol, firstCol, lastCol] = cols;
        const first = parseNums(firstCol);
        const last = parseNums(lastCol);
        if (first.length !== 5 || last.length !== 5) {
          setImportError(`Ligne ${i + 1} : il faut exactement 5 + 5 numéros.`);
          return;
        }
        if ([...first, ...last].some((n) => n < 1 || n > 90)) {
          setImportError(`Ligne ${i + 1} : les numéros doivent être compris entre 1 et 90.`);
          return;
        }
        imported.push({ drawNo: nextNo++, date: dateCol || todayFr(), first, last });
      }
      if (!imported.length) {
        setImportError("Aucun tirage valide trouvé dans le fichier.");
        return;
      }
      // Les plus récents en premier
      imported.reverse();
      setResults([...imported, ...results]);
      setImportSummary(`${imported.length} tirage(s) importé(s) avec succès.`);
    };
    reader.onerror = () => setImportError("Impossible de lire le fichier.");
    reader.readAsText(file);
  };

  const handleExportPDF = () => {
    const doc = new jsPDF();
    const orange: [number, number, number] = [220, 110, 30];
    const green: [number, number, number] = [40, 140, 70];
    const gray: [number, number, number] = [80, 80, 80];

    const headerY = 14;
    doc.setFontSize(18);
    doc.setTextColor(...orange);
    doc.text(`Tirage ${stats.name}`, 14, headerY);
    doc.setFontSize(10);
    doc.setTextColor(100, 100, 100);
    doc.text("Statistiques Loto 5/90 Côte d'Ivoire — Export complet", 14, headerY + 7);

    let nextY = headerY + 16;

    if (sections.stats) {
    // ---------- 1. Numéros les plus et moins souvent sortis — 5 premières places ----------
    autoTable(doc, {
      startY: nextY,
      head: [["Numéros les plus / moins souvent sortis — 5 premières places", "N°", "Sorties"]],
      body: [
        ...stats.firstPlace.most.map((e, i) => [
          i === 0 ? "N° le plus souvent sorti" : `${i + 1}e N° le plus souvent sorti`,
          String(e.num).padStart(2, "0"),
          String(e.freq),
        ]),
        ...stats.firstPlace.least.map((e, i) => [
          i === 0 ? "N° le moins souvent sorti" : `${i + 1}e N° le moins souvent sorti`,
          String(e.num).padStart(2, "0"),
          String(e.freq),
        ]),
      ],
      headStyles: { fillColor: orange, textColor: 255 },
      styles: { fontSize: 8 },
      margin: { left: 14, right: 14 },
    });

    nextY = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 8;

    // ---------- 2. Numéros les plus et moins souvent sortis — 5 dernières places ----------
    autoTable(doc, {
      startY: nextY,
      head: [["Numéros les plus / moins souvent sortis — 5 dernières places", "N°", "Sorties"]],
      body: [
        ...stats.lastPlace.most.map((e, i) => [
          i === 0 ? "N° le plus souvent sorti" : `${i + 1}e N° le plus souvent sorti`,
          String(e.num).padStart(2, "0"),
          String(e.freq),
        ]),
        ...stats.lastPlace.least.map((e, i) => [
          i === 0 ? "N° le moins souvent sorti" : `${i + 1}e N° le moins souvent sorti`,
          String(e.num).padStart(2, "0"),
          String(e.freq),
        ]),
      ],
      headStyles: { fillColor: orange, textColor: 255 },
      styles: { fontSize: 8 },
      margin: { left: 14, right: 14 },
    });

    nextY = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 8;
    }

    if (sections.hot) {
    // ---------- 3. Numéros chauds du moment — 5 premières places ----------
    autoTable(doc, {
      startY: nextY,
      head: [["Numéros chauds du moment — 5 premières places", "N°", "Occurrences"]],
      body: hotFirst.map((e, i) => [
        i === 0 ? "N° le plus souvent sorti" : `${i + 1}e N° le plus souvent sorti`,
        String(e.num).padStart(2, "0"),
        String(e.freq),
      ]),
      headStyles: { fillColor: green, textColor: 255 },
      styles: { fontSize: 8 },
      margin: { left: 14, right: 14 },
    });

    nextY = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 8;

    // ---------- 4. Numéros chauds du moment — 5 dernières places ----------
    autoTable(doc, {
      startY: nextY,
      head: [["Numéros chauds du moment — 5 dernières places", "N°", "Occurrences"]],
      body: hotLast.map((e, i) => [
        i === 0 ? "N° le plus souvent sorti" : `${i + 1}e N° le plus souvent sorti`,
        String(e.num).padStart(2, "0"),
        String(e.freq),
      ]),
      headStyles: { fillColor: green, textColor: 255 },
      styles: { fontSize: 8 },
      margin: { left: 14, right: 14 },
    });

    nextY = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 8;
    }

    if (sections.all) {
    // ---------- 5. Tous les numéros — 5 premières places (90 numéros) ----------
    autoTable(doc, {
      startY: nextY,
      head: [["Tous les numéros — 5 premières places", "N°", "Sorties"]],
      body: stats.allFirst.map((e) => [
        String(e.num).padStart(2, "0"),
        String(e.num).padStart(2, "0"),
        String(e.freq),
      ]),
      headStyles: { fillColor: gray, textColor: 255 },
      styles: { fontSize: 7 },
      margin: { left: 14, right: 14 },
      pageBreak: "auto",
    });

    nextY = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 8;

    // ---------- 6. Tous les numéros — 5 dernières places (90 numéros) ----------
    autoTable(doc, {
      startY: nextY,
      head: [["Tous les numéros — 5 dernières places", "N°", "Sorties"]],
      body: stats.allLast.map((e) => [
        String(e.num).padStart(2, "0"),
        String(e.num).padStart(2, "0"),
        String(e.freq),
      ]),
      headStyles: { fillColor: gray, textColor: 255 },
      styles: { fontSize: 7 },
      margin: { left: 14, right: 14 },
      pageBreak: "auto",
    });

    nextY = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 8;
    }

    if (sections.last25) {
    // ---------- 7. Résultats des 25 derniers tirages ----------
    autoTable(doc, {
      startY: nextY,
      head: [["Date", "5 premiers numéros", "5 derniers numéros"]],
      body: results.map((r) => [
        r.date,
        r.first.map((n) => String(n).padStart(2, "0")).join(", "),
        r.last.map((n) => String(n).padStart(2, "0")).join(", "),
      ]),
      headStyles: { fillColor: orange, textColor: 255 },
      styles: { fontSize: 8 },
      margin: { left: 14, right: 14 },
      pageBreak: "auto",
    });

    nextY = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 8;
    }

    if (sections.history) {
    // ---------- 8. Mini-historique complet du tirage ----------
    const periodStart = results.length ? results[results.length - 1].date : "—";
    const periodEnd = results.length ? results[0].date : "—";
    const totalDraws = results.length;

    // Résumé global
    autoTable(doc, {
      startY: nextY,
      head: [["Mini-historique complet du tirage", "Valeur"]],
      body: [
        ["Tirage", stats.name],
        ["Période couverte", `${periodStart} → ${periodEnd}`],
        ["Nombre total de tirages analysés", String(totalDraws)],
        [
          "Numéros les plus fréquents (1re place)",
          `${String(stats.firstPlace.most[0]?.num ?? "—").padStart(2, "0")} (${stats.firstPlace.most[0]?.freq ?? "—"} sorties)`,
        ],
        [
          "Numéros les moins fréquents (1re place)",
          `${String(stats.firstPlace.least[0]?.num ?? "—").padStart(2, "0")} (${stats.firstPlace.least[0]?.freq ?? "—"} sorties)`,
        ],
        [
          "Numéro chaud actuel (1re place)",
          `${String(hotFirst[0]?.num ?? "—").padStart(2, "0")} (${hotFirst[0]?.freq ?? "—"} occurrences sur 25 tirages)`,
        ],
      ],
      headStyles: { fillColor: orange, textColor: 255 },
      styles: { fontSize: 8 },
      margin: { left: 14, right: 14 },
    });

    // Historique chronologique condensé (tous les tirages sur une ligne par entrée)
    nextY = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 10;
    if (nextY > 260) {
      doc.addPage();
      nextY = 20;
    }

    doc.setFontSize(12);
    doc.setTextColor(...orange);
    doc.text("Historique chronologique complet", 14, nextY);
    doc.setFontSize(8);
    doc.setTextColor(60, 60, 60);
    doc.text("Tous les tirages analysés, du plus récent au plus ancien.", 14, nextY + 5);

    autoTable(doc, {
      startY: nextY + 10,
      head: [["Date", "Numéros tirés (10 au total)"]],
      body: results.map((r) => {
        const allNums = [...r.first, ...r.last]
          .map((n) => String(n).padStart(2, "0"))
          .join(", ");
        return [r.date, allNums];
      }),
      headStyles: { fillColor: green, textColor: 255 },
      styles: { fontSize: 8, cellPadding: 1.5 },
      margin: { left: 14, right: 14 },
      pageBreak: "auto",
    });
    }

    doc.save(`tirage-${stats.name}-complet.pdf`);
  };

  return (
    <div className="min-h-screen bg-background">
      <Head>
        <title>{stats.name ? `Tirage ${stats.name} — Statistiques Loto 5/90 Côte d'Ivoire` : "Tirage — Loto 5/90"}</title>
        <meta name="description" content={stats.name ? `Statistiques complètes du tirage ${stats.name} : numéros chauds, numéros les plus et moins sortis, et résultats des 25 derniers tirages.` : "Statistiques du tirage Loto 5/90."} />
      </Head>
      <DashboardHeader />

      <main className="mx-auto max-w-5xl px-4 py-8 sm:px-6">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <Link
            href="/"
            className="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground transition-colors hover:bg-muted"
          >
            <ArrowLeft className="h-4 w-4" />
            Retour au tableau de bord
          </Link>

        </div>


        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="mt-6 space-y-6"
        >
          {/* Title banner */}
          <div className="rounded-2xl border-2 border-dashed border-primary/50 bg-card p-6 text-center shadow-[var(--shadow-card)]">
            <h1 className="font-display text-2xl font-bold uppercase tracking-wide text-foreground sm:text-3xl">
              Tirage {stats.name}{stats.name && getDrawTime(stats.name) !== "99:99" ? ` - ${getDrawTime(stats.name).replace(':', 'H')}` : ""}
            </h1>
            <p className="mt-1 text-sm text-muted-foreground">
              Statistiques sur les 25 derniers tirages — Loto 5/90 Côte d'Ivoire
            </p>
          </div>

          <div className="flex flex-wrap items-center justify-center gap-2 mt-4">
            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
              <DialogTrigger asChild>
                <button className="inline-flex items-center gap-2 rounded-lg gradient-green px-4 py-2 text-sm font-semibold text-secondary-foreground transition-opacity hover:opacity-90">
                  <Plus className="h-4 w-4" />
                  Ajouter un tirage
                </button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Ajouter un tirage — {stats.name}</DialogTitle>
                </DialogHeader>
                <div className="space-y-4">
                  <div>
                    <label className="mb-1 block text-xs font-medium text-muted-foreground">
                      Date du tirage
                    </label>
                    <input
                      value={date}
                      onChange={(e) => setDate(e.target.value)}
                      placeholder="ex : 5 juin 2026"
                      className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary/40"
                    />
                  </div>
                  <div>
                    <label className="mb-1 block text-xs font-medium text-muted-foreground">
                      5 premiers numéros (séparés par un espace)
                    </label>
                    <input
                      value={firstStr}
                      onChange={(e) => setFirstStr(e.target.value)}
                      placeholder="ex : 12 47 8 63 29"
                      className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary/40"
                    />
                  </div>
                  <div>
                    <label className="mb-1 block text-xs font-medium text-muted-foreground">
                      5 derniers numéros (séparés par un espace)
                    </label>
                    <input
                      value={lastStr}
                      onChange={(e) => setLastStr(e.target.value)}
                      placeholder="ex : 5 81 34 19 70"
                      className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary/40"
                    />
                  </div>
                  {error && <p className="text-sm text-destructive">{error}</p>}
                </div>
                <DialogFooter>
                  <button
                    onClick={handleAddDraw}
                    className="inline-flex items-center gap-2 rounded-lg gradient-orange px-4 py-2 text-sm font-semibold text-primary-foreground shadow-[var(--shadow-glow)] transition-opacity hover:opacity-90"
                  >
                    <Plus className="h-4 w-4" />
                    Enregistrer le tirage
                  </button>
                </DialogFooter>
              </DialogContent>
            </Dialog>

            <Dialog
              open={importOpen}
              onOpenChange={(o) => {
                setImportOpen(o);
                if (!o) {
                  setImportError("");
                  setImportSummary("");
                }
              }}
            >
              <DialogTrigger asChild>
                <button className="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-semibold text-foreground transition-colors hover:bg-muted">
                  <Upload className="h-4 w-4" />
                  Importer
                </button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Importer des tirages — {stats.name}</DialogTitle>
                </DialogHeader>
                <div className="space-y-4">
                  <p className="text-sm text-muted-foreground">
                    Importez en masse vos tirages depuis un fichier CSV. Chaque ligne contient :
                    une date, les 5 premiers numéros et les 5 derniers numéros
                    (numéros séparés par un espace).
                  </p>
                  <button
                    onClick={handleDownloadSample}
                    className="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-sm font-medium text-foreground transition-colors hover:bg-muted"
                  >
                    <FileDown className="h-4 w-4" />
                    Télécharger le fichier exemple
                  </button>
                  <div>
                    <label className="mb-1 block text-xs font-medium text-muted-foreground">
                      Fichier CSV à importer
                    </label>
                    <input
                      type="file"
                      accept=".csv,text/csv,text/plain"
                      onChange={(e) => {
                        const f = e.target.files?.[0];
                        if (f) handleImportFile(f);
                        e.target.value = "";
                      }}
                      className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm file:mr-3 file:cursor-pointer file:rounded-md file:border-0 file:bg-primary file:px-3 file:py-1 file:text-sm file:font-medium file:text-primary-foreground outline-none focus:ring-2 focus:ring-primary/40"
                    />
                  </div>
                  {importError && <p className="text-sm text-destructive">{importError}</p>}
                  {importSummary && (
                    <p className="text-sm font-medium text-secondary-foreground">{importSummary}</p>
                  )}
                </div>
                <DialogFooter>
                  <button
                    onClick={() => setImportOpen(false)}
                    className="inline-flex items-center gap-2 rounded-lg gradient-orange px-4 py-2 text-sm font-semibold text-primary-foreground shadow-[var(--shadow-glow)] transition-opacity hover:opacity-90"
                  >
                    Terminer
                  </button>
                </DialogFooter>
              </DialogContent>
            </Dialog>

            <>
              <EditDrawModal history={results} onUpdateLocal={handleUpdateLocal} />
              <DeleteDrawModal history={results} onDeleteLocal={handleDeleteLocal} />
            </>

            <button 
              onClick={handleBulkSave}
              disabled={isSavingBulk || !results.some((r: any) => !r.id)}
              className="inline-flex items-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-sm font-semibold text-primary-foreground shadow-[var(--shadow-glow)] transition-opacity hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Save className="h-4 w-4" />
              {isSavingBulk ? "Enregistrement..." : "Enregistrer"}
            </button>

            <Dialog open={exportOpen} onOpenChange={setExportOpen}>
              <DialogTrigger asChild>
                <button className="inline-flex items-center gap-2 rounded-lg gradient-orange px-4 py-2 text-sm font-semibold text-primary-foreground shadow-[var(--shadow-glow)] transition-opacity hover:opacity-90">
                  <Download className="h-4 w-4" />
                  Exporter en PDF
                </button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Sections à inclure dans le PDF</DialogTitle>
                </DialogHeader>
                <div className="space-y-1">
                  {([
                    ["stats", "Numéros les plus / moins souvent sortis"],
                    ["hot", "Numéros chauds du moment"],
                    ["all", "Tous les numéros (grille complète)"],
                    ["last25", "Résultats des 25 derniers tirages"],
                    ["history", "Mini-historique complet"],
                  ] as const).map(([key, label]) => (
                    <label
                      key={key}
                      className="flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 transition-colors hover:bg-muted"
                    >
                      <input
                        type="checkbox"
                        checked={sections[key]}
                        onChange={() => toggleSection(key)}
                        className="h-4 w-4 accent-primary"
                      />
                      <span className="text-sm text-foreground">{label}</span>
                    </label>
                  ))}
                </div>
                <DialogFooter>
                  <button
                    onClick={() => {
                      handleExportPDF();
                      setExportOpen(false);
                    }}
                    disabled={!Object.values(sections).some(Boolean)}
                    className="inline-flex items-center gap-2 rounded-lg gradient-orange px-4 py-2 text-sm font-semibold text-primary-foreground shadow-[var(--shadow-glow)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    <Download className="h-4 w-4" />
                    Télécharger le PDF
                  </button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>


          {/* Plus / moins souvent sortis */}
          <SectionCard
            title="Numéros les plus et les moins souvent sortis"
            subtitle="Aux 5 premières places & aux 5 dernières places"
            icon={<BarChart3 className="h-5 w-5" />}
          >
            <div className="grid gap-6 md:grid-cols-2">
              <div>
                <p className="mb-2 text-center text-xs font-semibold uppercase tracking-wider text-primary">
                  … Aux 5 premières places
                </p>
                <RankedTable rank={stats.firstPlace} />
              </div>
              <div>
                <p className="mb-2 text-center text-xs font-semibold uppercase tracking-wider text-secondary">
                  … Aux 5 dernières places
                </p>
                <RankedTable rank={stats.lastPlace} />
              </div>
            </div>
          </SectionCard>

          {/* Numéros chauds */}
          <SectionCard
            title="Numéros chauds du moment"
            subtitle="Sur les 25 derniers tirages, nous retrouvons…"
            icon={<Flame className="h-5 w-5" />}
          >
            <div className="grid gap-6 md:grid-cols-2">
              <div>
                <p className="mb-2 text-center text-xs font-semibold uppercase tracking-wider text-primary">
                  … Aux 5 premières places
                </p>
                <HotList items={hotFirst} />
              </div>
              <div>
                <p className="mb-2 text-center text-xs font-semibold uppercase tracking-wider text-secondary">
                  … Aux 5 dernières places
                </p>
                <HotList items={hotLast} />
              </div>
            </div>
          </SectionCard>

          {/* Tous les numéros */}
          <SectionCard
            title="Tous les numéros"
            subtitle="Et leur nombre de sorties (entre parenthèses)"
            icon={<ListOrdered className="h-5 w-5" />}
          >
            <div className="grid gap-6 lg:grid-cols-2">
              <div>
                <p className="mb-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                  Parmi les 5 premières places
                </p>
                <AllNumbersGrid items={stats.allFirst} />
              </div>
              <div>
                <p className="mb-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                  Parmi les 5 dernières places
                </p>
                <AllNumbersGrid items={stats.allLast} />
              </div>
            </div>
          </SectionCard>

          {/* Résultats des 25 derniers tirages */}
          <SectionCard
            title="Résultats des 25 derniers tirages"
            subtitle="5 premiers chiffres tirés & 5 derniers chiffres tirés"
            icon={<CalendarRange className="h-5 w-5" />}
          >
            <div className="overflow-x-auto">
              <table className="w-full border-collapse text-sm">
                <thead>
                  <tr className="text-left text-[10px] uppercase tracking-wider text-muted-foreground">
                    <th className="px-2 pb-2 font-medium">Date</th>
                    <th className="px-2 pb-2 font-medium">5 premiers</th>
                    <th className="px-2 pb-2 font-medium">5 derniers</th>
                  </tr>
                </thead>
                <tbody>
                  {results.slice(0, 25).map((r) => (
                    <tr key={r.drawNo} className="border-t border-border/60">
                      <td className="whitespace-nowrap px-2 py-2 text-xs text-muted-foreground">
                        {r.date}
                      </td>
                      <td className="px-2 py-2">
                        <div className="flex gap-1">
                          {r.first.map((n) => (
                            <span
                              key={n}
                              className="flex h-6 w-6 items-center justify-center rounded-full bg-primary/10 text-[11px] font-bold text-primary tabular-nums"
                            >
                              {String(n).padStart(2, "0")}
                            </span>
                          ))}
                        </div>
                      </td>
                      <td className="px-2 py-2">
                        <div className="flex gap-1">
                          {r.last.map((n) => (
                            <span
                              key={n}
                              className="flex h-6 w-6 items-center justify-center rounded-full bg-secondary/10 text-[11px] font-bold text-secondary tabular-nums"
                            >
                              {String(n).padStart(2, "0")}
                            </span>
                          ))}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </SectionCard>

          {/* Historique de tous les tirages */}
          <SectionCard
            title="Historique de tous les tirages"
            subtitle="Tous les tirages analysés, du plus récent au plus ancien"
            icon={<ListOrdered className="h-5 w-5" />}
          >
            <div className="mb-4">
              <input
                type="text"
                placeholder="Rechercher par date ou par numéro (ex: 47, ou 12 45)..."
                value={historySearch}
                onChange={(e) => setHistorySearch(e.target.value)}
                className="w-full rounded-lg border border-border bg-background px-4 py-2 text-sm outline-none focus:ring-2 focus:ring-primary/40"
              />
            </div>
            <div className="overflow-x-auto">
              <table className="w-full border-collapse text-sm">
                <thead>
                  <tr className="text-left text-[10px] uppercase tracking-wider text-muted-foreground">
                    <th className="px-2 pb-2 font-medium">Date</th>
                    <th className="px-2 pb-2 font-medium">5 premiers</th>
                    <th className="px-2 pb-2 font-medium">5 derniers</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredHistory.map((r) => (
                    <tr key={r.drawNo} className="border-t border-border/60">
                      <td className="whitespace-nowrap px-2 py-2 text-xs text-muted-foreground">
                        {r.date}
                      </td>
                      <td className="px-2 py-2">
                        <div className="flex gap-1">
                          {r.first.map((n) => {
                            const isHighlighted = searchNums.includes(n);
                            return (
                              <span
                                key={n}
                                className={`flex h-6 w-6 items-center justify-center rounded-full text-[11px] font-bold tabular-nums transition-transform ${
                                  isHighlighted
                                    ? "scale-110 gradient-orange text-white shadow-[var(--shadow-glow)] ring-2 ring-primary ring-offset-1 ring-offset-background"
                                    : "bg-primary/10 text-primary"
                                }`}
                              >
                                {String(n).padStart(2, "0")}
                              </span>
                            );
                          })}
                        </div>
                      </td>
                      <td className="px-2 py-2">
                        <div className="flex gap-1">
                          {r.last.map((n) => {
                            const isHighlighted = searchNums.includes(n);
                            return (
                              <span
                                key={n}
                                className={`flex h-6 w-6 items-center justify-center rounded-full text-[11px] font-bold tabular-nums transition-transform ${
                                  isHighlighted
                                    ? "scale-110 gradient-orange text-white shadow-[var(--shadow-glow)] ring-2 ring-primary ring-offset-1 ring-offset-background"
                                    : "bg-secondary/10 text-secondary"
                                }`}
                              >
                                {String(n).padStart(2, "0")}
                              </span>
                            );
                          })}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </SectionCard>
        </motion.div>
      </main>
    </div>
  );
}
