import { useNavigate } from "react-router-dom";
import { useLiveQuery } from "dexie-react-hooks";
import * as Icons from "lucide-react";
import { games } from "../games";
import { db } from "../database/db";
import { motion } from "framer-motion";
import { NavigationMenu } from "../components/NavigationMenu";

// Kurzgesagt-style Planet Logo
const PlanetLogo = () => (
  <motion.div
    animate={{ y: [0, -12, 0], rotate: [0, 5, 0] }}
    transition={{ repeat: Infinity, duration: 5, ease: "easeInOut" }}
    className="relative w-28 h-28 flex items-center justify-center mb-4"
  >
    {/* The Planet Body */}
    <div className="absolute inset-0 bg-gradient-to-tr from-orange-600 to-yellow-400 rounded-full shadow-[inset_-8px_-8px_20px_rgba(0,0,0,0.2),0_10px_30px_rgba(245,158,11,0.5)]">
      {/* Craters */}
      <div className="absolute top-4 right-6 w-5 h-5 bg-orange-700/30 rounded-full shadow-[inset_2px_2px_4px_rgba(0,0,0,0.2)]" />
      <div className="absolute bottom-6 left-5 w-8 h-8 bg-orange-700/30 rounded-full shadow-[inset_2px_2px_4px_rgba(0,0,0,0.2)]" />
      <div className="absolute top-12 left-4 w-3 h-3 bg-orange-700/30 rounded-full shadow-[inset_1px_1px_2px_rgba(0,0,0,0.2)]" />
    </div>

    {/* The Planet Ring */}
    <div className="absolute w-36 h-10 border-[6px] border-yellow-200/90 rounded-[100%] transform -rotate-[20deg] shadow-[0_4px_10px_rgba(0,0,0,0.1)]" />

    {/* Center Icon */}
    <Icons.Dices className="w-12 h-12 text-white relative z-10 drop-shadow-md transform rotate-12" />
  </motion.div>
);

export default function Home() {
  const navigate = useNavigate();

  // Load unfinished games
  const activeSessions = useLiveQuery(() =>
    db.sessions.where("status").equals("playing").toArray(),
  );

  return (
    <div className="relative flex flex-col font-sans">
      <div className="relative z-10 p-4 space-y-8 pb-24">
        {/* Header Section */}
        <div className="flex items-center justify-between sticky top-4 z-50">
          <div className="flex items-center bg-background/40 backdrop-blur-md rounded-full shadow-sm p-0.5 border border-black/5 dark:border-white/5">
            <NavigationMenu />
          </div>
        </div>

        <header className="flex flex-col items-center justify-center pt-2 pb-6">
          <PlanetLogo />
          <h1 className="text-4xl font-black tracking-tighter text-foreground drop-shadow-sm">
            Board Score
          </h1>
        </header>

        {/* Active Game Section */}
        {activeSessions && activeSessions.length > 0 && (
          <section className="space-y-4">
            <div className="flex items-center justify-between px-2">
              <h2 className="text-xl font-bold tracking-tight text-foreground/90">
                Partie en cours
              </h2>
              <span className="flex h-3 w-3 relative">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-pink-400 opacity-75"></span>
                <span className="relative inline-flex rounded-full h-3 w-3 bg-pink-500"></span>
              </span>
            </div>

            <div className="space-y-4">
              {activeSessions.map((session) => {
                const game = games.find((g) => g.id === session.gameId);
                if (!game) return null;
                const GameIcon = game.icon
                  ? (Icons as any)[game.icon]
                  : Icons.Box;

                return (
                  <motion.div
                    key={session.id}
                    initial={{ opacity: 0, scale: 0.9 }}
                    animate={{ opacity: 1, scale: 1 }}
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                  >
                    <div
                      className="bg-gradient-to-r from-pink-500 to-orange-400 rounded-[2rem] p-1 shadow-xl cursor-pointer"
                      onClick={() => navigate(`/play/${session.id}`)}
                    >
                      <div className="bg-background/20 backdrop-blur-sm rounded-[1.8rem] p-4 flex items-center justify-between">
                        <div className="flex items-center space-x-4">
                          <div className="w-14 h-14 bg-white/20 rounded-2xl flex items-center justify-center shadow-inner">
                            {game.imagePath ? (
                              <img
                                src={game.imagePath}
                                alt={game.name}
                                className="w-8 h-8 object-contain"
                              />
                            ) : (
                              <GameIcon className="w-8 h-8 text-white" />
                            )}
                          </div>
                          <div>
                            <p className="font-black text-white text-lg leading-tight drop-shadow-sm">
                              {game.name}
                            </p>
                            <p className="text-sm text-white/90 font-medium">
                              {session.players.map((p) => p.name).join(", ")}
                            </p>
                          </div>
                        </div>
                        <div className="w-12 h-12 bg-white rounded-full flex items-center justify-center shadow-md">
                          <Icons.Play className="w-5 h-5 text-pink-500 ml-1" />
                        </div>
                      </div>
                    </div>
                  </motion.div>
                );
              })}
            </div>
          </section>
        )}

        {/* New Game Section */}
        <section className="space-y-4">
          <h2 className="text-xl font-bold tracking-tight px-2 text-foreground/90">
            Nouveau Jeu
          </h2>

          <div className="grid grid-cols-3 sm:grid-cols-4 gap-3 px-1">
            {games.map((game, index) => {
              const Icon = (Icons as any)[game.icon || "Box"] || Icons.Box;
              return (
                <motion.div
                  key={game.id}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{
                    delay: index * 0.05,
                    type: "spring",
                    stiffness: 150,
                    damping: 20,
                  }}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => navigate(`/new/${game.id}`)}
                  className="flex flex-col items-center gap-2 cursor-pointer group"
                >
                  <div
                    className="relative w-full aspect-square rounded-3xl shadow-lg flex items-center justify-center border-4 border-black/5 dark:border-white/5 overflow-hidden transition-all group-hover:shadow-2xl"
                    style={{
                      backgroundColor: game.imagePath
                        ? "transparent"
                        : game.colors.primary,
                    }}
                  >
                    {game.imagePath ? (
                      <div className="absolute inset-0 bg-white dark:bg-black/20">
                        <img
                          src={game.imagePath}
                          alt={`Logo ${game.name}`}
                          className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                        />
                      </div>
                    ) : (
                      <>
                        <div className="absolute -top-4 -right-4 w-16 h-16 rounded-full bg-white/10" />
                        <div className="absolute -bottom-2 -left-2 w-12 h-12 rounded-full bg-black/10" />
                        <Icon
                          className="w-12 h-12 text-white drop-shadow-md relative z-10"
                          strokeWidth={1.5}
                        />
                      </>
                    )}
                  </div>

                  <div className="text-center w-full">
                    <h3 className="font-bold text-xs leading-tight truncate px-1 drop-shadow-sm text-foreground/90">
                      {game.name}
                    </h3>
                  </div>
                </motion.div>
              );
            })}
          </div>
        </section>
      </div>
    </div>
  );
}
