import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { createGame, joinGame } from '../../api/gameApi';

const GameTest = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [gameCode, setGameCode] = useState('');
  const [createdGameCode, setCreatedGameCode] = useState('');
  const [showSuccess, setShowSuccess] = useState(false);

  const handleCreateGame = async () => {
    setLoading(true);
    setError(null);
    setShowSuccess(false);
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setError('Please login first at /login');
        return;
      }

      const gameData = {
        deckids: ['99333c9a-5928-4788-b852-fa482d34ce56'], // Test deck ID as array
        maxplayers: 4,
        logintype: 0, // 0=PUBLIC
      };

      const response = await createGame(gameData);
      console.log('Game created:', response);
      
      // Backend returns game object directly
      const code = response.gamecode || response.gameCode;
      if (code) {
        setCreatedGameCode(code);
        setShowSuccess(true);
      }
      
      // Store game token if provided
      if (response.gameToken) {
        localStorage.setItem('gameToken', response.gameToken);
      }
      
      // Wait 3 seconds to show code, then navigate
      setTimeout(() => {
        navigate('/lobby', { state: { gameCode: code } });
      }, 3000);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to create game');
      console.error('Create game error:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleJoinGame = async () => {
    setLoading(true);
    setError(null);
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setError('Kérlek jelentkezz be először a /login oldalon');
        return;
      }

      const joinData = {
        gameCode: gameCode.toUpperCase(),
        playerName: localStorage.getItem('username') || 'Test Player',
      };

      const response = await joinGame(joinData);
      console.log('Joined game:', response);
      
      // Store game token
      if (response.data?.gameToken) {
        localStorage.setItem('gameToken', response.data.gameToken);
        navigate('/lobby', { state: { gameCode: gameCode.toUpperCase() } });
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Nem sikerült csatlakozni a játékhoz');
      console.error('Join game error:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-900 text-white flex items-center justify-center p-8">
      <div className="bg-gray-800 rounded-lg p-8 max-w-md w-full">
        <h1 className="text-3xl font-bold mb-6 text-center">Game Test</h1>
        
        {error && (
          <div className="bg-red-500/20 border border-red-500 rounded p-3 mb-4">
            {error}
          </div>
        )}

        {showSuccess && createdGameCode && (
          <div className="bg-green-500/20 border border-green-500 rounded p-4 mb-4">
            <p className="font-bold text-lg mb-2">Game Created!</p>
            <p className="text-2xl font-mono tracking-wider text-green-400 mb-2">
              {createdGameCode}
            </p>
            <p className="text-sm text-gray-300">
              Share this code with other players so they can join!
            </p>
            <p className="text-sm text-gray-400 mt-2">
              Redirecting to game in 3 seconds...
            </p>
          </div>
        )}

        <div className="space-y-4">
          <button
            onClick={handleCreateGame}
            disabled={loading}
            className="w-full bg-green-600 hover:bg-green-700 disabled:bg-gray-600 text-white font-bold py-3 px-4 rounded transition"
          >
            {loading ? 'Creating...' : 'Create New Game'}
          </button>

          <div className="text-center text-gray-400">OR</div>

          <div>
            <input
              type="text"
              value={gameCode}
              onChange={(e) => setGameCode(e.target.value)}
              placeholder="Enter Game Code"
              className="w-full bg-gray-700 text-white px-4 py-2 rounded mb-2"
            />
            <button
              onClick={handleJoinGame}
              disabled={loading || !gameCode}
              className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-bold py-3 px-4 rounded transition"
            >
              {loading ? 'Joining...' : 'Join Game'}
            </button>
          </div>
        </div>

        <div className="mt-6 pt-6 border-t border-gray-700">
          <p className="text-sm text-gray-400 mb-2">Quick Access (Dev Only):</p>
          <button
            onClick={() => {
              localStorage.setItem('gameToken', 'test-token-123');
              navigate('/game');
            }}
            className="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded text-sm"
          >
            Go to Game (with test token)
          </button>
        </div>
      </div>
    </div>
  );
};

export default GameTest;
