import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  Moon,
  Sun,
  Monitor,
  Trash2,
  Download,
  Upload,
  FileSpreadsheet,
  LogIn,
  LogOut,
  RefreshCw,
  Check,
  CloudOff,
  Puzzle,
} from "lucide-react";
import { useAppStore } from "../stores/appStore";
import { useProfileStore } from "../stores/profileStore";
import { useAuthStore } from "../stores/authStore";
import { runSync, onSyncStatus, SyncStatus } from "../sync/syncEngine";
import { db } from "../database/db";
import { generateId } from "../utils/id";
import { getGameConfig } from "../games";
import { calculatePlayerTotalScore } from "../utils/scoring";
import { Card, CardContent } from "../components/ui/card";
import { Button } from "../components/ui/button";
import { PageHeader } from "../components/PageHeader";

export default function Settings() {
  const { theme, setTheme } = useAppStore();
  const navigate = useNavigate();
  const { user, status, logout } = useAuthStore();
  const [syncStatus, setSyncStatus] = useState<SyncStatus>("idle");

  useEffect(() => onSyncStatus(setSyncStatus), []);

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

  const handleImportJson = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "application/json";
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = async (event) => {
        try {
          const content = event.target?.result as string;
          const data = JSON.parse(content);

          if (!data.sessions || !data.settings || !data.players) {
            throw new Error("Fichier de sauvegarde invalide ou corrompu.");
          }

          const locations = data.locations || [];
          const importedGames = data.importedGames || [];
          let profiles = data.profiles || [];

          // Rétrocompatibilité : un ancien backup n'a pas de profils.
          // On crée un profil de secours et on y rattache les données héritées.
          if (profiles.length === 0) {
            const now = Date.now();
            const fallbackId = generateId();
            profiles = [
              { id: fallbackId, name: "Moi", createdAt: now, updatedAt: now },
            ];
            data.sessions.forEach((s: any) => {
              if (!s.profileId) s.profileId = fallbackId;
            });
            data.players.forEach((p: any) => {
              if (!p.profileId) p.profileId = fallbackId;
            });
            locations.forEach((l: any) => {
              if (!l.profileId) l.profileId = fallbackId;
            });
            data.settings.forEach((st: any) => {
              if (!st.activeProfileId) st.activeProfileId = fallbackId;
            });
          }

          if (
            window.confirm(
              "Attention : L'importation va écraser vos données actuelles. Voulez-vous continuer ?",
            )
          ) {
            await db.transaction(
              "rw",
              [
                db.sessions,
                db.settings,
                db.players,
                db.locations,
                db.profiles,
                db.syncState,
                db.importedGames,
              ],
              async () => {
                await db.sessions.clear();
                await db.settings.clear();
                await db.players.clear();
                await db.locations.clear();
                await db.profiles.clear();
                await db.syncState.clear();
                await db.importedGames.clear();

                if (data.sessions.length > 0)
                  await db.sessions.bulkAdd(data.sessions);
                if (data.settings.length > 0)
                  await db.settings.bulkAdd(data.settings);
                if (data.players.length > 0)
                  await db.players.bulkAdd(data.players);
                if (locations.length > 0)
                  await db.locations.bulkAdd(locations);
                if (profiles.length > 0)
                  await db.profiles.bulkAdd(profiles);
                if (importedGames.length > 0)
                  await db.importedGames.bulkAdd(importedGames);
              },
            );

            // Reload settings to apply any imported theme
            const newSettings = await db.settings.get(1);
            if (newSettings && newSettings.theme) {
              setTheme(newSettings.theme);
            }

            alert("Restauration réussie !");
            window.location.reload();
          }
        } catch (error) {
          console.error(error);
          alert(
            "Échec de l'importation : Le fichier n'est pas un backup Skori valide.",
          );
        }
      };
      reader.readAsText(file);
    };
    input.click();
  };

  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 = `skori-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 les parties de ce profil ? Cette action est irréversible.",
      )
    ) {
      const activeProfileId = useProfileStore.getState().activeProfileId;
      if (!activeProfileId) return;
      // Soft-delete the active profile's sessions so the reset propagates on sync.
      const now = Date.now();
      await db.sessions
        .where("profileId")
        .equals(activeProfileId)
        .modify({ deletedAt: now });
      alert("Données réinitialisées.");
    }
  };

  return (
    <div className="p-5 space-y-6 relative z-10">
      <PageHeader title="Paramètres" />

      <section className="space-y-4">
        <h2 className="text-xl font-bold px-2 tracking-tight">Compte</h2>
        <Card className="border-0 shadow-lg bg-background/90 backdrop-blur-md">
          <CardContent className="p-4">
            {status === "authenticated" && user ? (
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="min-w-0">
                    <p className="font-black text-lg truncate">
                      {user.displayName}
                    </p>
                    <p className="text-sm text-muted-foreground truncate">
                      {user.email}
                    </p>
                  </div>
                  <span className="flex items-center text-xs font-bold text-emerald-600 bg-emerald-500/10 px-3 py-1.5 rounded-full shrink-0">
                    {syncStatus === "syncing" ? (
                      <>
                        <RefreshCw className="w-3.5 h-3.5 mr-1 animate-spin" />
                        Sync…
                      </>
                    ) : syncStatus === "error" ? (
                      <span className="flex items-center text-destructive">
                        <CloudOff className="w-3.5 h-3.5 mr-1" />
                        Erreur
                      </span>
                    ) : (
                      <>
                        <Check className="w-3.5 h-3.5 mr-1" />
                        Synchronisé
                      </>
                    )}
                  </span>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <Button
                    variant="outline"
                    className="rounded-2xl font-bold"
                    onClick={() => runSync()}
                    disabled={syncStatus === "syncing"}
                  >
                    <RefreshCw className="w-4 h-4 mr-2" />
                    Synchroniser
                  </Button>
                  <Button
                    variant="outline"
                    className="rounded-2xl font-bold text-destructive hover:bg-destructive/10"
                    onClick={() => logout()}
                  >
                    <LogOut className="w-4 h-4 mr-2" />
                    Déconnexion
                  </Button>
                </div>
              </div>
            ) : (
              <div className="space-y-3">
                <p className="text-sm text-muted-foreground">
                  Connectez-vous pour sauvegarder et synchroniser vos parties
                  entre vos appareils.
                </p>
                <Button
                  className="w-full h-12 rounded-2xl font-black"
                  onClick={() => navigate("/login")}
                >
                  <LogIn className="w-5 h-5 mr-2" />
                  Se connecter / Créer un compte
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </section>

      <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">Jeux</h2>
        <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={() => navigate("/games")}
        >
          <div className="flex items-center font-black text-lg w-full">
            <div className="w-10 h-10 rounded-full bg-indigo-500/20 flex items-center justify-center mr-4">
              <Puzzle className="w-5 h-5 text-indigo-600" />
            </div>
            Gérer les jeux importés
          </div>
        </Button>
      </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>

          <div className="grid grid-cols-2 gap-3 mt-3">
            <Button
              variant="outline"
              className="w-full justify-start h-auto py-3 px-4 border-0 shadow-md bg-background/90 backdrop-blur-md rounded-2xl hover:scale-[1.02] transition-transform"
              onClick={handleExportJson}
            >
              <div className="flex flex-col items-center text-center w-full">
                <div className="w-10 h-10 rounded-full bg-blue-500/20 flex items-center justify-center mb-2">
                  <Download className="w-5 h-5 text-blue-600" />
                </div>
                <span className="font-bold text-sm">Sauvegarder</span>
                <span className="text-[10px] text-muted-foreground mt-0.5">
                  Format .json
                </span>
              </div>
            </Button>

            <Button
              variant="outline"
              className="w-full justify-start h-auto py-3 px-4 border-0 shadow-md bg-background/90 backdrop-blur-md rounded-2xl hover:scale-[1.02] transition-transform"
              onClick={handleImportJson}
            >
              <div className="flex flex-col items-center text-center w-full">
                <div className="w-10 h-10 rounded-full bg-purple-500/20 flex items-center justify-center mb-2">
                  <Upload className="w-5 h-5 text-purple-600" />
                </div>
                <span className="font-bold text-sm">Restaurer</span>
                <span className="text-[10px] text-muted-foreground mt-0.5">
                  À partir d'un .json
                </span>
              </div>
            </Button>
          </div>

          <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">
        Skori v1.0.0
      </div>
    </div>
  );
}
