"use client";
import React from "react";
import { Button } from "@/components/ui/button";
import { useGameStore } from "@/lib/store/game-store";
import { InfoIcon, XIcon } from "lucide-react";
import GameConfigForm from "./game-config-form";
import GameVariantSelector from "./game-variant-selector";
import { api } from "@/trpc/react";
import { useLobbyStore } from "@/lib/store/lobby-store";

function GameConfigurator() {
  const updateGameConfig = api.gameConfig.update.useMutation();
  const selectGame = useGameStore((state) => state.setSelectedGame);
  const selectedGame = useGameStore((state) => state.selectedGame);
  const setGameConfig = useGameStore((state) => state.setGameConfig);
  const gameConfig = useGameStore((state) => state.gameConfig);
  const lobbyId = useLobbyStore((state) => state.lobby.id);
  const handleUnselectGame = () => {
    selectGame(undefined);
    updateGameConfig.mutate({
      lobbyId,
      config: {
        ...gameConfig,
        gameId: undefined,
      },
    });
  };

  return (
    <div className="flex size-full flex-col justify-between p-6">
      <div className="space-y-2">
        <div className="flex items-center">
          <h2 className="text-xl font-semibold">
            {selectedGame?.name ?? "Select a game to get started"}
          </h2>
          {selectedGame && (
            <Button size={"icon"} variant={"ghost"} className="ml-auto">
              <InfoIcon className="size-4" />
            </Button>
          )}
        </div>

        {selectedGame && (
          <>
            <GameVariantSelector />
            <GameConfigForm />
          </>
        )}
      </div>

      {selectedGame && (
        <div className="flex items-center gap-2">
          <Button>Start Game</Button>
          <Button
            variant={"ghost"}
            size={"icon"}
            className="ml-auto"
            onClick={handleUnselectGame}
          >
            <XIcon className="size-4" />
          </Button>
        </div>
      )}
    </div>
  );
}

export default GameConfigurator;
