import { useState, useMemo } from "react";
import { useLiveQuery } from "dexie-react-hooks";
import { db } from "../../database/db";
import { useProfileStore } from "../../stores/profileStore";
import { useAllGames } from "../../games";
import { Card, CardContent } from "../../components/ui/card";
import { Badge } from "../../components/ui/badge";
import { PageHeader } from "../../components/PageHeader";
import { Trophy, Clock, Gamepad2, Medal, Filter } from "lucide-react";
import { Avatar } from "../../components/ui/avatar";
import { motion } from "framer-motion";

export default function Statistics() {
  const activeProfileId = useProfileStore((s) => s.activeProfileId);
  const games = useAllGames();
  const allSessions =
    useLiveQuery(
      async () => {
        if (!activeProfileId) return [];
        return db.sessions
          .where("profileId")
          .equals(activeProfileId)
          .and((s) => !s.deletedAt)
          .toArray();
      },
      [activeProfileId],
    ) || [];
  const players =
    useLiveQuery(
      async () => {
        if (!activeProfileId) return [];
        return db.players
          .where("profileId")
          .equals(activeProfileId)
          .and((p) => !p.deletedAt)
          .toArray();
      },
      [activeProfileId],
    ) || [];

  const [timeFilter, setTimeFilter] = useState<"all" | "7d" | "30d" | "year">(
    "all",
  );
  const [selectedPlayerIds, setSelectedPlayerIds] = useState<string[]>([]);
  const [selectedGameId, setSelectedGameId] = useState<string>("all");

  const togglePlayerFilter = (playerId: string) => {
    setSelectedPlayerIds((prev) =>
      prev.includes(playerId)
        ? prev.filter((id) => id !== playerId)
        : [...prev, playerId],
    );
  };

  // 1. Filter sessions based on criteria
  const sessions = useMemo(() => {
    let filtered = allSessions;

    // Filter by Time
    const now = Date.now();
    if (timeFilter === "7d") {
      filtered = filtered.filter((s) => s.dateStart > now - 7 * 86400000);
    } else if (timeFilter === "30d") {
      filtered = filtered.filter((s) => s.dateStart > now - 30 * 86400000);
    } else if (timeFilter === "year") {
      const startOfYear = new Date(new Date().getFullYear(), 0, 1).getTime();
      filtered = filtered.filter((s) => s.dateStart > startOfYear);
    }

    // Filter by Players (Must include ALL selected players to allow "Head to Head" stats)
    if (selectedPlayerIds.length > 0) {
      filtered = filtered.filter((s) =>
        selectedPlayerIds.every((selectedId) =>
          s.players.some((p) => p.id === selectedId),
        ),
      );
    }

    // Filter by Game
    if (selectedGameId !== "all") {
      filtered = filtered.filter((s) => s.gameId === selectedGameId);
    }

    return filtered;
  }, [allSessions, timeFilter, selectedPlayerIds, selectedGameId]);

  // 2. Calculate Global Stats
  const totalGames = sessions.length;
  const finishedGames = sessions.filter((s) => s.status === "finished");

  let totalDurationMinutes = 0;
  finishedGames.forEach((s) => {
    if (s.dateEnd && s.dateStart) {
      totalDurationMinutes += Math.round((s.dateEnd - s.dateStart) / 60000);
    }
  });

  const averageDuration =
    finishedGames.length > 0
      ? Math.round(totalDurationMinutes / finishedGames.length)
      : 0;

  // 2. Favorite Game
  const gameCounts: Record<string, number> = {};
  sessions.forEach((s) => {
    gameCounts[s.gameId] = (gameCounts[s.gameId] || 0) + 1;
  });

  let favoriteGameId = "";
  let maxGameCount = 0;
  for (const [id, count] of Object.entries(gameCounts)) {
    if (count > maxGameCount) {
      maxGameCount = count;
      favoriteGameId = id;
    }
  }
  const favoriteGame = games.find((g) => g.id === favoriteGameId);

  // 3. Player Stats (Winrate & Games Played & Cabo calls & Kamikaze)
  const playerStats: Record<
    string,
    {
      id: string;
      name: string;
      played: number;
      won: number;
      avatar?: string;
      caboSuccess: number;
      caboFails: number;
      kamikaze: number;
    }
  > = {};

  // Initialize with known players
  players.forEach((p) => {
    playerStats[p.id] = {
      id: p.id,
      name: p.name,
      played: 0,
      won: 0,
      avatar: p.avatar,
      caboSuccess: 0,
      caboFails: 0,
      kamikaze: 0,
    };
  });

  finishedGames.forEach((session) => {
    session.players.forEach((p) => {
      if (!playerStats[p.id]) {
        playerStats[p.id] = {
          id: p.id,
          name: p.name,
          played: 0,
          won: 0,
          avatar: p.avatar,
          caboSuccess: 0,
          caboFails: 0,
          kamikaze: 0,
        };
      }
      playerStats[p.id].played += 1;
    });

    session.winnerIds?.forEach((winnerId) => {
      if (playerStats[winnerId]) {
        playerStats[winnerId].won += 1;
      }
    });

    // Count Cabo calls & Kamikaze
    if (session.gameId === "cabo") {
      session.rounds.forEach((round) => {
        round.scores.forEach((score) => {
          if (score.caboCall === "success" && playerStats[score.playerId]) {
            playerStats[score.playerId].caboSuccess += 1;
          }
          if (score.caboCall === "fail" && playerStats[score.playerId]) {
            playerStats[score.playerId].caboFails += 1;
          }
          if (score.kamikaze && playerStats[score.playerId]) {
            playerStats[score.playerId].kamikaze += 1;
          }
        });
      });
    }
  });

  const leaderboard = Object.values(playerStats)
    .filter((stat) => stat.played > 0)
    .map((stat) => ({
      ...stat,
      winrate: stat.played > 0 ? Math.round((stat.won / stat.played) * 100) : 0,
    }))
    .sort((a, b) => b.winrate - a.winrate || b.played - a.played); // Sort by winrate, then games played

  // 4. Hide unselected players from leaderboard if any are selected
  const displayLeaderboard =
    selectedPlayerIds.length > 0
      ? leaderboard.filter((stat) => selectedPlayerIds.includes(stat.id))
      : leaderboard;

  return (
    <div className="p-5 space-y-5 relative z-10">
      <PageHeader title="Stats" />

      {/* Filters */}
      <section className="space-y-3 bg-secondary/30 p-3 rounded-2xl border border-border/50">
        <div className="flex items-center space-x-2 text-sm font-medium text-muted-foreground">
          <Filter className="w-4 h-4" />
          <span>Filtres</span>
        </div>

        <div className="flex gap-2">
          <select
            className="flex-1 p-2 border rounded-xl bg-background text-sm truncate"
            value={timeFilter}
            onChange={(e) => setTimeFilter(e.target.value as any)}
          >
            <option value="all">Depuis toujours</option>
            <option value="7d">7 derniers jours</option>
            <option value="30d">30 derniers jours</option>
            <option value="year">Cette année</option>
          </select>

          <select
            className="flex-1 p-2 border rounded-xl bg-background text-sm truncate"
            value={selectedGameId}
            onChange={(e) => setSelectedGameId(e.target.value)}
          >
            <option value="all">Tous les jeux</option>
            {games.map((g) => (
              <option key={g.id} value={g.id}>
                {g.name}
              </option>
            ))}
          </select>
        </div>

        {players.length > 0 && (
          <div className="flex overflow-x-auto pb-1 -mx-3 px-3 gap-2 hide-scrollbar">
            {players.map((player) => (
              <Badge
                key={player.id}
                variant={
                  selectedPlayerIds.includes(player.id) ? "default" : "outline"
                }
                className="shrink-0 px-3 py-1.5 cursor-pointer text-sm font-normal active:scale-95 transition-all"
                onClick={() => togglePlayerFilter(player.id)}
              >
                {player.name}
              </Badge>
            ))}
          </div>
        )}
      </section>

      {/* Hero Stats */}
      <div className="grid grid-cols-2 gap-3">
        <div className="rounded-[1.5rem] bg-card/70 backdrop-blur-xl border border-black/5 dark:border-white/10 shadow-sm p-4 flex flex-col items-center text-center">
          <div className="w-10 h-10 rounded-full grid place-items-center mb-2 bg-primary/15 text-primary">
            <Gamepad2 className="w-5 h-5" />
          </div>
          <div className="text-3xl font-black tracking-tight leading-none">
            {totalGames}
          </div>
          <div className="text-[11px] font-bold text-muted-foreground mt-1.5 uppercase tracking-wide">
            Parties jouées
          </div>
        </div>

        <div className="rounded-[1.5rem] bg-card/70 backdrop-blur-xl border border-black/5 dark:border-white/10 shadow-sm p-4 flex flex-col items-center text-center">
          <div className="w-10 h-10 rounded-full grid place-items-center mb-2 bg-amber-500/15 text-amber-500">
            <Clock className="w-5 h-5" />
          </div>
          <div className="text-3xl font-black tracking-tight leading-none">
            {averageDuration}
            <span className="text-lg">m</span>
          </div>
          <div className="text-[11px] font-bold text-muted-foreground mt-1.5 uppercase tracking-wide">
            Durée moyenne
          </div>
        </div>
      </div>

      {favoriteGame && selectedGameId === "all" && (
        <section className="space-y-3">
          <h2 className="text-lg font-semibold px-1">Jeu préféré</h2>
          <Card className="border-primary/20">
            <CardContent className="p-4 flex items-center space-x-4">
              <div
                className="w-16 h-16 rounded-2xl flex items-center justify-center shrink-0"
                style={{
                  backgroundColor: `${favoriteGame.colors.primary}20`,
                  color: favoriteGame.colors.primary,
                }}
              >
                <Trophy className="w-8 h-8" />
              </div>
              <div>
                <h3 className="font-bold text-xl">{favoriteGame.name}</h3>
                <p className="text-muted-foreground">
                  {maxGameCount} parties terminées
                </p>
              </div>
            </CardContent>
          </Card>
        </section>
      )}

      {selectedGameId === "cabo" && (
        <section className="space-y-3">
          <h2 className="text-lg font-semibold px-1">
            Statistiques spéciales (Cabo)
          </h2>
          <div className="grid gap-3">
            {displayLeaderboard
              .filter(
                (p) => p.caboSuccess > 0 || p.caboFails > 0 || p.kamikaze > 0,
              )
              .sort((a, b) => b.caboSuccess - a.caboSuccess)
              .map((player) => (
                <Card
                  key={`cabo-${player.id}`}
                  className="overflow-hidden bg-gradient-to-r from-green-500/10 via-background to-transparent border-green-500/20"
                >
                  <CardContent className="p-3 flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <span className="font-semibold">{player.name}</span>
                    </div>
                    <div className="flex items-center gap-4 text-sm font-medium">
                      <div className="flex flex-col items-center">
                        <span className="text-amber-600 font-bold text-lg">
                          {player.kamikaze}
                        </span>
                        <span className="text-xs text-muted-foreground">
                          Kamikazes
                        </span>
                      </div>
                      <div className="w-px h-8 bg-border"></div>
                      <div className="flex flex-col items-center">
                        <span className="text-green-600 font-bold text-lg">
                          {player.caboSuccess}
                        </span>
                        <span className="text-xs text-muted-foreground">
                          Cabos+
                        </span>
                      </div>
                      <div className="w-px h-8 bg-border"></div>
                      <div className="flex flex-col items-center">
                        <span className="text-destructive font-bold text-lg">
                          {player.caboFails}
                        </span>
                        <span className="text-xs text-muted-foreground">
                          Cabos-
                        </span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
          </div>
        </section>
      )}

      {/* Leaderboard — winrate as horizontal bars (single hue) */}
      <section className="space-y-3">
        <h2 className="text-lg font-black tracking-tight px-1 flex items-center">
          <Medal className="w-5 h-5 mr-2 text-primary" />
          Classement (taux de victoire)
        </h2>

        {displayLeaderboard.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">
            <Medal className="w-10 h-10 mx-auto mb-2 opacity-20" />
            <p className="text-sm font-medium">
              {allSessions.length === 0
                ? "Terminez des parties pour voir le classement."
                : "Aucune partie ne correspond à ces filtres."}
            </p>
          </div>
        ) : (
          <div className="rounded-[1.75rem] bg-card/70 backdrop-blur-xl border border-black/5 dark:border-white/10 shadow-sm p-4 space-y-4">
            {displayLeaderboard.map((player, index) => (
              <motion.div
                key={player.id}
                initial={{ opacity: 0, x: -12 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: index * 0.06 }}
                className="space-y-1.5"
              >
                <div className="flex items-center gap-2.5">
                  <span
                    className={`w-6 h-6 rounded-full grid place-items-center text-[11px] font-black shrink-0 ${
                      index === 0
                        ? "bg-amber-400 text-amber-950"
                        : index === 1
                          ? "bg-slate-300 text-slate-800"
                          : index === 2
                            ? "bg-amber-700 text-amber-50"
                            : "bg-secondary text-muted-foreground"
                    }`}
                  >
                    {index + 1}
                  </span>
                  <Avatar src={player.avatar} name={player.name} size="sm" />
                  <span className="font-bold truncate flex-1">{player.name}</span>
                  <span className="font-black text-primary tabular-nums shrink-0">
                    {player.winrate}%
                  </span>
                </div>
                {/* Bar: thin track + rounded teal fill anchored to the baseline */}
                <div className="h-2.5 rounded-full bg-secondary/70 dark:bg-white/10 overflow-hidden ml-[34px]">
                  <motion.div
                    className="h-full rounded-full bg-primary"
                    initial={{ width: 0 }}
                    animate={{ width: `${Math.max(player.winrate, 2)}%` }}
                    transition={{ delay: index * 0.06 + 0.1, type: "spring", stiffness: 90, damping: 18 }}
                  />
                </div>
                <p className="text-[11px] text-muted-foreground ml-[34px]">
                  {player.won} victoire{player.won > 1 ? "s" : ""} · {player.played} partie
                  {player.played > 1 ? "s" : ""}
                </p>
              </motion.div>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}
