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

const StartGame = () => {
  const { userId } = useContext(UserContext);
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    // Parse userId to ensure it's a number
    const parsedUserId = parseInt(userId);

    if (!parsedUserId) {
      setError('You must be logged in to create a game.');
      return;
    }

    if (!name || !description) {
      setError('Game name and description are required.');
      return;
    }

    try {
      const response = await fetch('http://localhost:5000/createGame', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name,
          description,
          gameMasterId: parsedUserId, // Use parsed ID
          participants: [], 
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        setError(errorData.error || 'Failed to create game.');
        return;
      }

      const data = await response.json();
      setSuccess('Game created successfully!');
      navigate(`/games/${data.gameId}/master`); // Navigate to game master page directly
    } catch (err) {
      setError('Something went wrong. Please try again.');
    }
  };

  return (
    <div className="create-game-page">
      <h1>Erstelle ein neues Spiel</h1>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="gameName">Spiel Name</label>
          <input
            type="text"
            id="gameName"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Füge den Spielnamen ein"
            required
          />
        </div>
        <div className="form-group">
          <label htmlFor="gameDescription">Spiel Beschreibung</label>
          <textarea
            id="gameDescription"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Füge eine Beschreibung ein"
            required
          />
        </div>
        {error && <p className="error-message">{error}</p>}
        {success && <p className="success-message">{success}</p>}
        <button type="submit">Starte Spiel</button>
      </form>
    </div>
  );
};

export default StartGame;
