import {
  Moon,
  Sun,
  Monitor,
  Trash2,
  Download,
  FileSpreadsheet,
} from "lucide-react";
import { useAppStore } from "../stores/appStore";
import { db } from "../database/db";
import { getGameConfig } from "../games";
import { calculatePlayerTotalScore } from "../utils/scoring";
import { Card, CardContent } from "../components/ui/card";
import { Button } from "../components/ui/button";
import { NavigationMenu } from "../components/NavigationMenu";

export default function Settings() {
  const { theme, setTheme } = useAppStore();

  const handleExportJson = async () => {
    try {
      const sessions = await db.sessions.toArray();
      const settings = await db.settings.toArray();
      const players = await db.players.toArray();
      const data = JSON.stringify({ sessions, settings, players });
      const blob = new Blob([data], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `boardscore-backup-${new Date().toISOString().split("T")[0]}.json`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (e) {
      alert("Erreur lors de l'exportation technique.");
    }
  };

  const handleExportCSV = async () => {
    try {
      const sessions = await db.sessions.toArray();

      // Trier du plus récent au plus ancien
      sessions.sort((a, b) => b.dateStart - a.dateStart);

      // Ajouter le BOM UTF-8 pour qu'Excel lise correctement les accents
      let csv = "\uFEFF";
      csv += "Date;Jeu;Durée (min);Manches;Statut;Joueur;Score;Victoire\n";

      sessions.forEach((session) => {
        const gameConfig = getGameConfig(session.gameId);
        const gameName = gameConfig?.name || session.gameId;
        const date = new Date(session.dateStart).toLocaleString("fr-FR");
        const duration = session.dateEnd
          ? Math.round((session.dateEnd - session.dateStart) / 60000).toString()
          : "";
        const status = session.status === "finished" ? "Terminée" : "En cours";
        const rounds = session.rounds.length;

        session.players.forEach((p) => {
          const score = calculatePlayerTotalScore(
            p.id,
            session.rounds,
            gameConfig,
            true,
          );
          const isWinner = session.winnerIds?.includes(p.id) ? "Oui" : "Non";

          // Echapper les guillemets pour le CSV
          const safeGameName = `"${gameName.replace(/"/g, '""')}"`;
          const safePlayerName = `"${p.name.replace(/"/g, '""')}"`;

          csv += `${date};${safeGameName};${duration};${rounds};${status};${safePlayerName};${score};${isWinner}\n`;
        });
      });

      const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `boardscore-historique-${new Date().toISOString().split("T")[0]}.csv`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (e) {
      alert("Erreur lors de l'exportation CSV.");
    }
  };

  const handleReset = async () => {
    if (
      window.confirm(
        "Êtes-vous sûr de vouloir supprimer TOUTES vos parties ? Cette action est irréversible.",
      )
    ) {
      await db.sessions.clear();
      alert("Données réinitialisées.");
    }
  };

  return (
    <div className="p-4 space-y-6 pb-20 relative z-50">
      <header className="py-1 px-1 flex items-center bg-background/40 backdrop-blur-md rounded-full shadow-sm w-max pr-6 sticky top-4 z-50 border border-black/5 dark:border-white/5">
        <NavigationMenu />
        <h1 className="text-2xl font-black tracking-tighter ml-2 drop-shadow-sm">
          Paramètres
        </h1>
      </header>

      <section className="space-y-4">
        <h2 className="text-xl font-bold px-2 tracking-tight">Apparence</h2>
        <Card className="border-0 shadow-lg bg-background/90 backdrop-blur-md">
          <CardContent className="p-3 flex items-center justify-between gap-3">
            <Button
              variant={theme === "light" ? "default" : "ghost"}
              className={`flex-1 flex flex-col items-center h-auto py-5 rounded-[1.5rem] transition-all ${theme === "light" ? "bg-amber-400 text-amber-950 hover:bg-amber-500 hover:scale-105" : "bg-black/5 dark:bg-white/5 hover:bg-black/10"}`}
              onClick={() => setTheme("light")}
            >
              <Sun
                className={`w-8 h-8 mb-3 ${theme === "light" ? "animate-[spin_10s_linear_infinite]" : ""}`}
              />
              <span className="font-bold">Clair</span>
            </Button>
            <Button
              variant={theme === "dark" ? "default" : "ghost"}
              className={`flex-1 flex flex-col items-center h-auto py-5 rounded-[1.5rem] transition-all ${theme === "dark" ? "bg-indigo-600 text-white hover:bg-indigo-700 hover:scale-105" : "bg-black/5 dark:bg-white/5 hover:bg-black/10"}`}
              onClick={() => setTheme("dark")}
            >
              <Moon
                className={`w-8 h-8 mb-3 ${theme === "dark" ? "animate-pulse" : ""}`}
              />
              <span className="font-bold">Sombre</span>
            </Button>
            <Button
              variant={theme === "system" ? "default" : "ghost"}
              className={`flex-1 flex flex-col items-center h-auto py-5 rounded-[1.5rem] transition-all ${theme === "system" ? "bg-slate-700 text-white hover:bg-slate-800 hover:scale-105" : "bg-black/5 dark:bg-white/5 hover:bg-black/10"}`}
              onClick={() => setTheme("system")}
            >
              <Monitor className="w-8 h-8 mb-3" />
              <span className="font-bold">Auto</span>
            </Button>
          </CardContent>
        </Card>
      </section>

      <section className="space-y-4">
        <h2 className="text-xl font-bold px-2 tracking-tight">Données</h2>
        <div className="space-y-3">
          <Button
            variant="outline"
            className="w-full justify-start h-auto py-4 px-6 border-0 shadow-md bg-background/90 backdrop-blur-md rounded-[1.5rem] hover:scale-[1.02] transition-transform"
            onClick={handleExportCSV}
          >
            <div className="flex flex-col items-start text-left w-full">
              <span className="flex items-center font-black text-lg">
                <div className="w-10 h-10 rounded-full bg-emerald-500/20 flex items-center justify-center mr-4">
                  <FileSpreadsheet className="w-5 h-5 text-emerald-600" />
                </div>
                Exporter l'historique (CSV)
              </span>
              <span className="text-sm text-muted-foreground ml-14">
                Format tableur (Excel, Sheets)
              </span>
            </div>
          </Button>

          <Button
            variant="outline"
            className="w-full justify-start h-auto py-4 px-6 border-0 shadow-md bg-background/90 backdrop-blur-md rounded-[1.5rem] hover:scale-[1.02] transition-transform"
            onClick={handleExportJson}
          >
            <div className="flex flex-col items-start text-left w-full">
              <span className="flex items-center font-black text-lg">
                <div className="w-10 h-10 rounded-full bg-blue-500/20 flex items-center justify-center mr-4">
                  <Download className="w-5 h-5 text-blue-600" />
                </div>
                Sauvegarde complète (.json)
              </span>
              <span className="text-sm text-muted-foreground ml-14">
                Copie brute de l'application
              </span>
            </div>
          </Button>

          <Button
            variant="outline"
            className="w-full justify-start h-auto py-4 px-6 border-0 shadow-md bg-destructive/10 backdrop-blur-md rounded-[1.5rem] hover:scale-[1.02] transition-transform text-destructive hover:bg-destructive/20 mt-4"
            onClick={handleReset}
          >
            <div className="flex items-center font-black text-lg w-full">
              <div className="w-10 h-10 rounded-full bg-destructive/20 flex items-center justify-center mr-4">
                <Trash2 className="w-5 h-5 text-destructive" />
              </div>
              Réinitialiser tout
            </div>
          </Button>
        </div>
      </section>

      <div className="pt-12 pb-6 text-center text-sm font-bold text-muted-foreground/60">
        Board Score v1.0.0
      </div>
    </div>
  );
}
