import { useNavigate } from "react-router-dom";
import * as Icons from "lucide-react";
import { Trophy, MapPin } from "lucide-react";
import { motion } from "framer-motion";
import { GameConfig, GameSession, Location } from "../types";
import { calculatePlayerTotalScore } from "../utils/scoring";
import { Avatar } from "./ui/avatar";

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

// A finished-game "activity" card for the Home feed and History list.
export function SessionCard({
  session,
  game,
  location,
}: {
  session: GameSession;
  game: GameConfig;
  location?: Location;
}) {
  const navigate = useNavigate();
  const GameIcon = (Icons as any)[game.icon || "Box"] || Icons.Box;
  const playing = session.status === "playing";

  const ranked = session.players
    .map((p) => ({
      p,
      score: calculatePlayerTotalScore(p.id, session.rounds, game, true),
      win: session.winnerIds?.includes(p.id),
    }))
    .sort((a, b) =>
      game.scoreType === "negative" ? a.score - b.score : b.score - a.score,
    );
  const winner = ranked.find((r) => r.win) || ranked[0];

  return (
    <motion.button
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      whileTap={{ scale: 0.99 }}
      onClick={() =>
        navigate(playing ? `/play/${session.id}` : `/gameover/${session.id}`)
      }
      className="w-full text-left rounded-[1.75rem] bg-card/70 backdrop-blur-xl border border-black/5 dark:border-white/10 shadow-sm p-4 space-y-3"
    >
      <div className="flex items-center gap-3">
        <div
          className="w-10 h-10 rounded-xl flex items-center justify-center overflow-hidden shrink-0 ring-1 ring-black/5 dark:ring-white/10"
          style={{
            backgroundColor: game.imagePath ? "transparent" : game.colors.primary,
          }}
        >
          {game.imagePath ? (
            <img src={game.imagePath} alt={game.name} className="w-full h-full object-cover" />
          ) : (
            <GameIcon className="w-5 h-5 text-white" />
          )}
        </div>
        <div className="min-w-0 flex-1">
          <p className="font-black tracking-tight leading-tight truncate">
            {game.name}
          </p>
          <p className="text-xs text-muted-foreground flex items-center gap-2 flex-wrap">
            <span>{formatDate(session.dateStart)}</span>
            {location && (
              <span className="inline-flex items-center">
                <MapPin className="w-3 h-3 mr-0.5" />
                {location.name}
              </span>
            )}
          </p>
        </div>
        {playing && (
          <span className="text-[10px] font-black uppercase tracking-wide bg-pink-500 text-white px-2 py-1 rounded-full animate-pulse shrink-0">
            En cours
          </span>
        )}
      </div>

      {!playing && ranked.length > 0 && (
        <>
          <div className="flex items-center justify-between bg-primary/10 dark:bg-primary/20 rounded-2xl px-3 py-2">
            <div className="flex items-center gap-2 min-w-0">
              <Trophy className="w-4 h-4 text-amber-500 shrink-0" fill="currentColor" />
              <Avatar src={winner.p.avatar} name={winner.p.name} size="sm" />
              <span className="font-bold truncate">{winner.p.name}</span>
            </div>
            <span className="font-black text-primary shrink-0">{winner.score}</span>
          </div>

          {ranked.length > 1 && (
            <div className="flex flex-wrap gap-1.5">
              {ranked
                .filter((r) => r !== winner)
                .map((r) => (
                  <span
                    key={r.p.id}
                    className="text-xs font-bold bg-black/5 dark:bg-white/10 text-foreground/80 rounded-lg px-2 py-1"
                  >
                    {r.p.name} · {r.score}
                  </span>
                ))}
            </div>
          )}
        </>
      )}

      {playing && (
        <p className="text-sm text-muted-foreground font-medium truncate">
          {session.players.map((p) => p.name).join(", ")}
        </p>
      )}
    </motion.button>
  );
}
