import React, { useState, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { UserContext } from '../context/UserContext';

const JoinGamePage = () => {
  const [gameCode, setGameCode] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate();
  const { userId } = useContext(UserContext);

  // Handle form submission
  const handleJoinGame = async (e) => {
    e.preventDefault();

    if (gameCode.trim() === '') {
      setError('Please enter a game code');
      return;
    }

    try {
      const response = await axios.post(`http://localhost:5000/joinGame/${gameCode}`, { userId });
      if (response.status === 201) {
        setError('');
          navigate(`/games/${gameCode}`); // Redirect to the games page
      } else {
        setError('Failed to join the game.');
      }
    } catch (err) {
      setError(err.response ? err.response.data.error : 'Error joining the game');
    }
  };

  return (
    <div className="join-game-container">
      <h1>Join a Game</h1>
      <form onSubmit={handleJoinGame}>
        <input
          type="text"
          placeholder="Enter Game Code"
          value={gameCode}
          onChange={(e) => setGameCode(e.target.value)}
        />
        <button type="submit">Join Game</button>
      </form>
      {error && <p className="error">{error}</p>}
    </div>
  );
};

export default JoinGamePage;