import { useNavigate } from "react-router-dom";
import { useLiveQuery } from "dexie-react-hooks";
import { db } from "../database/db";
import { games } from "../games";
import { Card, CardContent } from "../components/ui/card";
import { NavigationMenu } from "../components/NavigationMenu";

import { motion } from "framer-motion";

function formatDate(ms: number) {
  const d = new Date(ms);
  return d.toLocaleDateString("fr-FR", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

export default function History() {
  const navigate = useNavigate();
  const sessions = useLiveQuery(() =>
    db.sessions.orderBy("dateStart").reverse().toArray(),
  );

  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">
          Historique
        </h1>
      </header>

      {!sessions || sessions.length === 0 ? (
        <div className="text-center text-muted-foreground py-10 bg-background/60 backdrop-blur-sm rounded-[2rem]">
          Aucune partie enregistrée.
        </div>
      ) : (
        <div className="space-y-4">
          {sessions.map((session, index) => {
            const game = games.find((g) => g.id === session.gameId);
            if (!game) return null;

            return (
              <motion.div
                key={session.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{
                  delay: index * 0.05,
                  type: "spring",
                  stiffness: 100,
                }}
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <div
                  className="bg-gradient-to-r p-1 rounded-[2rem] shadow-lg cursor-pointer"
                  style={{
                    backgroundImage: `linear-gradient(to right, ${game.colors.primary}, ${game.colors.primary}80)`,
                  }}
                  onClick={() =>
                    navigate(
                      session.status === "playing"
                        ? `/play/${session.id}`
                        : `/gameover/${session.id}`,
                    )
                  }
                >
                  <Card className="border-0 bg-background/90 backdrop-blur-md m-0 h-full w-full">
                    <CardContent className="p-4 flex items-center justify-between">
                      <div className="w-full">
                        <div className="flex justify-between items-start mb-2">
                          <h3
                            className="font-black text-xl leading-tight"
                            style={{ color: game.colors.primary }}
                          >
                            {game.name}
                          </h3>
                          <span
                            className={`text-xs font-bold px-2 py-1 rounded-full ${session.status === "playing" ? "bg-pink-500 text-white animate-pulse" : "bg-secondary text-muted-foreground"}`}
                          >
                            {session.status === "playing"
                              ? "En cours"
                              : "Terminée"}
                          </span>
                        </div>
                        <p className="text-sm text-foreground/70 font-medium mb-2">
                          {formatDate(session.dateStart)}
                        </p>
                        <div className="flex flex-wrap gap-1.5 mt-1">
                          {session.players.map((p) => {
                            const isWinner = session.winnerIds?.includes(p.id);
                            return (
                              <span
                                key={p.id}
                                className={`text-xs px-2 py-1 rounded-md font-bold ${isWinner ? "bg-yellow-400 text-yellow-900 shadow-sm" : "bg-black/5 dark:bg-white/10 text-foreground/80"}`}
                              >
                                {isWinner ? "🏆 " : ""}
                                {p.name}
                              </span>
                            );
                          })}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </div>
              </motion.div>
            );
          })}
        </div>
      )}
    </div>
  );
}
