import { useNavigate } from "react-router-dom";
import { useLiveQuery } from "dexie-react-hooks";
import * as Icons from "lucide-react";
import { Play, Trophy, Gamepad2, CalendarDays, Clock } from "lucide-react";
import { motion } from "framer-motion";
import { useAllGames } from "../games";
import { db } from "../database/db";
import { PlanetMark } from "../components/Logo";
import { ProfileMenu } from "../components/ProfileMenu";
import { SessionCard } from "../components/SessionCard";
import { useProfileStore } from "../stores/profileStore";
import { GameSession } from "../types";

function StatTile({
  icon: Icon,
  value,
  label,
  tint,
}: {
  icon: any;
  value: string | number;
  label: string;
  tint: string;
}) {
  return (
    <div className="flex-1 rounded-[1.5rem] bg-card/70 backdrop-blur-xl border border-black/5 dark:border-white/10 shadow-sm p-3.5 flex flex-col items-center text-center">
      <div
        className="w-9 h-9 rounded-full grid place-items-center mb-2"
        style={{ backgroundColor: `${tint}22`, color: tint }}
      >
        <Icon className="w-[18px] h-[18px]" />
      </div>
      <span className="text-2xl font-black tracking-tight leading-none">
        {value}
      </span>
      <span className="text-[11px] font-bold text-muted-foreground mt-1 uppercase tracking-wide">
        {label}
      </span>
    </div>
  );
}

export default function Home() {
  const navigate = useNavigate();
  const activeProfileId = useProfileStore((s) => s.activeProfileId);
  const games = useAllGames();

  const sessions = useLiveQuery(
    async () => {
      if (!activeProfileId) return [];
      const arr = await db.sessions
        .where("profileId")
        .equals(activeProfileId)
        .and((s) => !s.deletedAt)
        .sortBy("dateStart");
      return arr.reverse();
    },
    [activeProfileId],
  );
  const locations = useLiveQuery(() => db.locations.toArray()) || [];

  const all = sessions || [];
  const active = all.filter((s) => s.status === "playing");
  const finished = all.filter((s) => s.status === "finished");

  const startOfMonth = new Date(
    new Date().getFullYear(),
    new Date().getMonth(),
    1,
  ).getTime();
  const thisMonth = finished.filter((s) => s.dateStart >= startOfMonth).length;
  const totalMinutes = finished.reduce(
    (sum, s) =>
      sum + (s.dateEnd ? Math.round((s.dateEnd - s.dateStart) / 60000) : 0),
    0,
  );
  const playTime =
    totalMinutes >= 60
      ? `${Math.round(totalMinutes / 60)}h`
      : `${totalMinutes}m`;

  const gameOf = (s: GameSession) => games.find((g) => g.id === s.gameId);

  return (
    <div className="relative flex flex-col font-sans">
      <div className="relative z-10 px-5 pt-5 pb-28 space-y-6">
        {/* Header */}
        <header className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <PlanetMark size={34} />
            <span className="text-2xl font-black tracking-tighter">Skori</span>
          </div>
          <ProfileMenu />
        </header>

        {/* Stat tiles */}
        <div className="flex gap-3">
          <StatTile icon={Gamepad2} value={finished.length} label="Parties" tint="#14b8a6" />
          <StatTile icon={CalendarDays} value={thisMonth} label="Ce mois" tint="#f59e0b" />
          <StatTile icon={Clock} value={playTime} label="Temps de jeu" tint="#8b5cf6" />
        </div>

        {/* Resume in-progress */}
        {active.length > 0 && (
          <section className="space-y-3">
            <div className="flex items-center gap-2 px-1">
              <span className="flex h-2.5 w-2.5 relative">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-pink-400 opacity-75" />
                <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-pink-500" />
              </span>
              <h2 className="text-lg font-black tracking-tight">Reprendre</h2>
            </div>
            {active.map((session) => {
              const game = gameOf(session);
              if (!game) return null;
              const GameIcon = (Icons as any)[game.icon || "Box"] || Icons.Box;
              return (
                <motion.button
                  key={session.id}
                  whileTap={{ scale: 0.98 }}
                  onClick={() => navigate(`/play/${session.id}`)}
                  className="w-full text-left rounded-[1.75rem] p-4 flex items-center justify-between shadow-lg relative overflow-hidden"
                  style={{
                    backgroundImage: `linear-gradient(120deg, ${game.colors.primary}, ${game.colors.primary}cc)`,
                  }}
                >
                  <div className="absolute -right-6 -top-8 w-28 h-28 rounded-full bg-white/10" />
                  <div className="flex items-center gap-4 relative z-10">
                    <div className="w-14 h-14 rounded-2xl bg-white/20 backdrop-blur-sm flex items-center justify-center shadow-inner overflow-hidden">
                      {game.imagePath ? (
                        <img src={game.imagePath} alt={game.name} className="w-9 h-9 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 truncate max-w-[190px]">
                        {session.players.map((p) => p.name).join(", ")}
                      </p>
                    </div>
                  </div>
                  <div className="w-11 h-11 bg-white rounded-full flex items-center justify-center shadow-md relative z-10 shrink-0">
                    <Play className="w-5 h-5 ml-0.5" style={{ color: game.colors.primary }} fill="currentColor" />
                  </div>
                </motion.button>
              );
            })}
          </section>
        )}

        {/* Quick start */}
        <section className="space-y-3">
          <h2 className="text-lg font-black tracking-tight px-1">Nouvelle partie</h2>
          <div className="flex gap-3 overflow-x-auto pb-2 -mx-5 px-5 hide-scrollbar">
            {games.map((game) => {
              const Icon = (Icons as any)[game.icon || "Box"] || Icons.Box;
              return (
                <motion.button
                  key={game.id}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => navigate(`/new/${game.id}`)}
                  className="shrink-0 w-[84px] flex flex-col items-center gap-2 group"
                >
                  <div
                    className="w-[84px] h-[84px] rounded-[1.4rem] shadow-md flex items-center justify-center overflow-hidden ring-1 ring-black/5 dark:ring-white/10 transition-shadow group-hover:shadow-xl"
                    style={{ backgroundColor: game.imagePath ? "transparent" : game.colors.primary }}
                  >
                    {game.imagePath ? (
                      <img src={game.imagePath} alt={game.name} className="w-full h-full object-cover" />
                    ) : (
                      <Icon className="w-10 h-10 text-white drop-shadow-md" strokeWidth={1.5} />
                    )}
                  </div>
                  <span className="text-[11px] font-bold leading-tight truncate max-w-full text-foreground/90">
                    {game.name}
                  </span>
                </motion.button>
              );
            })}
          </div>
        </section>

        {/* Recent activity feed */}
        <section className="space-y-3">
          <h2 className="text-lg font-black tracking-tight px-1">Activité récente</h2>
          {finished.length === 0 ? (
            <div className="text-center text-muted-foreground py-10 bg-card/50 backdrop-blur-sm rounded-[1.75rem] border border-black/5 dark:border-white/10">
              <Trophy className="w-10 h-10 mx-auto mb-2 opacity-20" />
              <p className="text-sm font-medium">
                Vos parties terminées apparaîtront ici.
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {finished.slice(0, 8).map((session) => {
                const game = gameOf(session);
                if (!game) return null;
                const location = session.locationId
                  ? locations.find((l) => l.id === session.locationId)
                  : undefined;
                return (
                  <SessionCard
                    key={session.id}
                    session={session}
                    game={game}
                    location={location}
                  />
                );
              })}
            </div>
          )}
        </section>
      </div>
    </div>
  );
}
