import type { IMinigame } from "@/game-engien";
import { gameLibary } from "@/game-engien/games";
import { useGameStore } from "@/lib/store/game-store";
import { useLobbyStore } from "@/lib/store/lobby-store";
import { cn } from "@/lib/utils";
import { api } from "@/trpc/react";
import Image from "next/image";
import React from "react";
import { toast } from "sonner";

function GameSelector({ isAdmin }: { isAdmin: boolean }) {
  const updateGameConfig = api.gameConfig.update.useMutation();
  const selectedGame = useGameStore((state) => state.selectedGame);
  const setSelectedGame = useGameStore((state) => state.setSelectedGame);
  const gameConfig = useGameStore((state) => state.gameConfig);
  const lobbyId = useLobbyStore((state) => state.lobby.id);
  const handleGameSelect = (game: IMinigame) => {
    if (!isAdmin) return toast.error("Only admins can change games");
    setSelectedGame(game);
    updateGameConfig.mutate({
      lobbyId,
      config: {
        ...gameConfig,
        gameId: game.id,
      },
    });
  };
  return (
    <div className="grid w-full grid-cols-4 gap-4">
      {gameLibary.map((game) => (
        <GameCard
          key={game.id}
          game={game}
          selected={selectedGame?.id === game.id}
          onClick={() => handleGameSelect(game)}
        />
      ))}
    </div>
  );
}
const GameCard = ({
  game,
  selected,
  onClick,
}: {
  game: IMinigame;
  selected?: boolean;
  onClick?: () => void;
}) => {
  return (
    <div
      className={cn(
        "container-bg group w-full cursor-pointer items-center justify-between space-y-1 overflow-hidden",
        selected &&
          "before:bg-primary/40 before:absolute before:inset-0 before:-z-10 before:w-full before:animate-pulse before:rounded-md before:blur-xl",
      )}
      onClick={onClick}
    >
      <div className="relative h-20 w-full">
        <Image
          fill
          alt="game-image"
          src={game.thumbnail}
          className={cn(
            "object-cover opacity-50 transition-all duration-300 ease-in-out group-hover:opacity-90",
            selected && "opacity-100",
          )}
        />
      </div>
      <div className="flex items-center gap-2 px-4 pb-4">
        <div>
          <h4 className="font-meidum text-xl font-bold">{game.name}</h4>
          <div className="text-xs text-white/75">{game.description}</div>
        </div>
      </div>
    </div>
  );
};

export default GameSelector;
