import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Trophy, Home, Share2, RotateCcw, Clock, MapPin } from "lucide-react";
import * as Icons from "lucide-react";
import { useLiveQuery } from "dexie-react-hooks";
import { db } from "../database/db";
import { GameSession } from "../types";
import { useGameConfig } from "../games";
import { useGameStore } from "../stores/gameStore";
import { useGameTheme } from "../hooks/useGameTheme";
import { Button } from "../components/ui/button";
import { Card, CardContent } from "../components/ui/card";
import { Avatar } from "../components/ui/avatar";
import { motion } from "framer-motion";
import { calculatePlayerTotalScore } from "../utils/scoring";
import { CelebrationOverlay } from "../components/CelebrationOverlay";
import { generateId } from "../utils/id";

export default function GameOver() {
  const { sessionId } = useParams<{ sessionId: string }>();
  const navigate = useNavigate();
  const [session, setSession] = useState<GameSession | null>(null);
  const [showCelebration, setShowCelebration] = useState(true);
  const startNewGame = useGameStore((state) => state.startNewGame);

  const gameConfig = useGameConfig(session?.gameId);
  useGameTheme(gameConfig);

  const location = useLiveQuery(
    () =>
      session?.locationId ? db.locations.get(session.locationId) : undefined,
    [session?.locationId],
  );

  useEffect(() => {
    if (sessionId) {
      db.sessions.get(sessionId).then((data) => {
        if (data) setSession(data);
      });
    }

    // Stop celebration after 5 seconds to let the user scroll and click buttons
    const timer = setTimeout(() => {
      setShowCelebration(false);
    }, 5000);

    return () => clearTimeout(timer);
  }, [sessionId]);

  if (!session)
    return <div className="p-4 text-center mt-10">Chargement...</div>;

  const Icon = gameConfig?.icon ? (Icons as any)[gameConfig.icon] : null;

  // Effective scoring categories (may depend on the session's options).
  const categories =
    gameConfig?.getScoringCategories?.(session.options) ??
    gameConfig?.scoringCategories;

  const durationInMinutes = session.dateEnd
    ? Math.round((session.dateEnd - session.dateStart) / 60000)
    : 0;

  const calculateTotalScore = (playerId: string) => {
    return calculatePlayerTotalScore(
      playerId,
      session.rounds,
      gameConfig,
      true,
    );
  };

  const totals = session.players.map((p) => {
    // If it's a categorized game (Harmonies), extract details from the first (and only) round
    let details = undefined;
    if (categories && session.rounds.length > 0) {
      const pScore = session.rounds[0].scores.find((s) => s.playerId === p.id);
      details = pScore?.details;
    }

    return {
      player: p,
      score: calculateTotalScore(p.id),
      details: details,
      isWinner: session.winnerIds?.includes(p.id),
    };
  });

  // Sort by score
  if (gameConfig?.scoreType === "negative") {
    totals.sort((a, b) => a.score - b.score);
  } else {
    totals.sort((a, b) => b.score - a.score);
  }

  const handleShare = async () => {
    const text =
      `Partie de ${gameConfig?.name}\n\n` +
      totals
        .map((t, i) => `${i + 1}. ${t.player.name} : ${t.score} pts`)
        .join("\n");

    if (navigator.share) {
      try {
        await navigator.share({
          title: "Résultat de la partie",
          text: text,
        });
      } catch (e) {}
    } else {
      navigator.clipboard.writeText(text);
      alert("Résultats copiés dans le presse-papier !");
    }
  };

  const handleReplay = async () => {
    if (!session || !gameConfig) return;

    // Create new players array with new IDs but same names and avatars
    const newPlayers = session.players.map((p) => ({
      id: generateId(),
      name: p.name,
      avatar: p.avatar,
    }));

    const newSessionId = await startNewGame(
      gameConfig.id,
      newPlayers,
      session.options,
      session.profileId,
      session.locationId,
    );
    navigate(`/play/${newSessionId}`);
  };

  // Trouver le vainqueur principal (le premier dans le tableau trié)
  const topWinner = totals.find((t) => t.isWinner)?.player;

  return (
    <div className="flex flex-col min-h-screen bg-background pb-40">
      {/* 💥 Animation de Célébration (disparaît après qq secondes) */}
      {showCelebration && topWinner && (
        <CelebrationOverlay winner={topWinner} gameId={gameConfig?.id || ""} />
      )}

      {/* Hero Banner with Winner */}
      <div className="w-[100vw] ml-[calc(50%-50vw)] bg-primary/10 border-b relative overflow-hidden flex flex-col items-center justify-center pt-12 pb-16 shadow-inner">
        {gameConfig?.bannerPath ? (
          <>
            <div
              className="absolute inset-0 opacity-40 pointer-events-none bg-cover bg-center"
              style={{ backgroundImage: `url(${gameConfig.bannerPath})` }}
            />
            <div className="absolute inset-0 bg-gradient-to-b from-background/40 to-background pointer-events-none" />
          </>
        ) : (
          <div className="absolute inset-0 opacity-10 pointer-events-none">
            {Icon && (
              <Icon className="w-full h-full text-primary scale-150 transform translate-x-1/4 translate-y-1/4" />
            )}
          </div>
        )}

        <motion.div
          initial={{ scale: 0.8, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          className="relative z-10 flex flex-col items-center text-center px-4 max-w-xl mx-auto"
        >
          <div className="w-24 h-24 bg-background rounded-full shadow-lg flex items-center justify-center mb-6 border-4 border-primary overflow-hidden">
            {gameConfig?.imagePath ? (
              <img
                src={gameConfig.imagePath}
                alt={`Logo ${gameConfig.name}`}
                className="w-full h-full object-cover"
              />
            ) : Icon ? (
              <Icon className="w-12 h-12 text-primary" strokeWidth={1.5} />
            ) : (
              <Trophy className="w-12 h-12 text-primary" />
            )}
          </div>
          <div>
            <h1 className="text-4xl font-black tracking-tight mb-2">
              Partie Terminée
            </h1>
            <p className="text-lg font-medium text-primary bg-background/50 px-4 py-1 rounded-full inline-block backdrop-blur-sm shadow-sm">
              {gameConfig?.name}
            </p>
          </div>

          <div className="flex items-center flex-wrap justify-center gap-2 mt-6">
            <div className="flex items-center text-sm font-medium text-muted-foreground bg-background px-4 py-2 rounded-full shadow-sm border">
              <Clock className="w-4 h-4 mr-2" />
              {durationInMinutes} minutes • {session.rounds.length} manches
            </div>
            {session.locationId && (
              <div className="flex items-center text-sm font-medium text-muted-foreground bg-background px-4 py-2 rounded-full shadow-sm border">
                <MapPin className="w-4 h-4 mr-2" />
                {location?.name ?? "—"}
              </div>
            )}
          </div>
        </motion.div>
      </div>

      <div className="space-y-4 flex-1 p-4 mt-2">
        <h2 className="text-xl font-semibold px-2">Classement</h2>
        <div className="space-y-3">
          {totals.map((t, index) => (
            <motion.div
              key={t.player.id}
              initial={{ x: -20, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              transition={{ delay: index * 0.1 }}
            >
              <Card
                className={`overflow-hidden ${t.isWinner ? "border-primary border-2 shadow-md" : ""}`}
              >
                <CardContent className="p-0 flex items-stretch">
                  <div
                    className={`w-12 flex items-center justify-center font-bold text-lg ${t.isWinner ? "bg-primary text-primary-foreground" : "bg-secondary text-muted-foreground"}`}
                  >
                    #{index + 1}
                  </div>
                  <div className="flex-1 p-4 flex flex-col justify-center">
                    <div className="flex items-center justify-between w-full">
                      <div className="flex items-center space-x-3">
                        <Avatar
                          src={t.player.avatar}
                          name={t.player.name}
                          size="md"
                        />
                        <span className="font-semibold text-lg">
                          {t.player.name}
                        </span>
                      </div>
                      <span className="text-2xl font-bold">{t.score}</span>
                    </div>
                    {/* Display details if it's a categorized game like Harmonies */}
                    {t.details && categories && (
                      <div className="mt-3 pt-3 border-t border-border/50 grid grid-cols-3 gap-2">
                        {categories.map((cat) => {
                          const val = t.details?.[cat.id];
                          if (!val || val === "0") return null;
                          const CatIcon = cat.icon
                            ? (Icons as any)[cat.icon]
                            : null;
                          return (
                            <div
                              key={cat.id}
                              className="flex flex-col items-center bg-secondary/30 rounded-lg p-1.5"
                            >
                              {CatIcon && (
                                <CatIcon
                                  className="w-4 h-4 mb-0.5"
                                  style={{ color: cat.color ?? "currentColor" }}
                                  strokeWidth={2.2}
                                />
                              )}
                              <span className="text-[10px] text-muted-foreground truncate w-full text-center">
                                {cat.label}
                              </span>
                              <span className="text-sm font-bold">{val}</span>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          ))}
        </div>

        {/* Round-by-round detail (multi-round games) */}
        {session.rounds.length > 1 && (
          <section className="pt-2">
            <h2 className="text-xl font-semibold px-2 mb-2">
              Détail des manches
            </h2>
            <Card className="overflow-hidden">
              <CardContent className="p-0 overflow-x-auto">
                <table className="w-full text-sm border-collapse">
                  <thead>
                    <tr className="border-b border-border/60">
                      <th className="text-left font-black text-muted-foreground px-3 py-2.5 sticky left-0 bg-card z-10">
                        Manche
                      </th>
                      {session.players.map((p) => (
                        <th
                          key={p.id}
                          className="px-3 py-2.5 text-right font-bold whitespace-nowrap"
                        >
                          {p.name}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {session.rounds.map((round) => (
                      <tr
                        key={round.id}
                        className="border-b border-border/30 last:border-0"
                      >
                        <td className="px-3 py-2 font-bold text-muted-foreground sticky left-0 bg-card z-10">
                          #{round.roundNumber}
                        </td>
                        {session.players.map((p) => {
                          const s = round.scores.find(
                            (sc) => sc.playerId === p.id,
                          );
                          return (
                            <td
                              key={p.id}
                              className="px-3 py-2 text-right tabular-nums"
                            >
                              {s ? s.score : "—"}
                              {s?.caboCall === "success" && (
                                <span className="ml-1 text-[10px] text-green-600 font-bold">
                                  ✓
                                </span>
                              )}
                              {s?.caboCall === "fail" && (
                                <span className="ml-1 text-[10px] text-destructive font-bold">
                                  ✗
                                </span>
                              )}
                              {s?.kamikaze && (
                                <span className="ml-1 text-[10px] text-amber-600 font-bold">
                                  K
                                </span>
                              )}
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                    <tr className="bg-secondary/50 font-black">
                      <td className="px-3 py-2.5 sticky left-0 bg-secondary/50 z-10">
                        Total
                      </td>
                      {session.players.map((p) => (
                        <td
                          key={p.id}
                          className="px-3 py-2.5 text-right tabular-nums text-primary"
                        >
                          {calculateTotalScore(p.id)}
                        </td>
                      ))}
                    </tr>
                  </tbody>
                </table>
              </CardContent>
            </Card>
          </section>
        )}
      </div>

      <div className="fixed bottom-0 left-0 right-0 z-50 p-4 bg-background/95 backdrop-blur-md border-t flex flex-wrap gap-3 justify-center max-w-md mx-auto">
        <Button variant="outline" className="flex-1" onClick={handleReplay}>
          <RotateCcw className="w-4 h-4 mr-2" />
          Rejouer
        </Button>
        <Button variant="outline" className="flex-1" onClick={handleShare}>
          <Share2 className="w-4 h-4 mr-2" />
          Partager
        </Button>
        <Button className="w-full" onClick={() => navigate("/")}>
          <Home className="w-4 h-4 mr-2" />
          Retour Accueil
        </Button>
      </div>
    </div>
  );
}
