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

const startGame = () => {
  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('');

    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: 1, 
          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}`); // Redirect to the game details page
    } catch (err) {
      setError('Something went wrong. Please try again.');
    }
  };

  return (
    <div className="create-game-page">
      <h1>Create a New Game</h1>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="gameName">Game Name</label>
          <input
            type="text"
            id="gameName"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Enter game name"
            required
          />
        </div>
        <div className="form-group">
          <label htmlFor="gameDescription">Game Description</label>
          <textarea
            id="gameDescription"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Enter game description"
            required
          />
        </div>
        {error && <p className="error-message">{error}</p>}
        {success && <p className="success-message">{success}</p>}
        <button type="submit">Create Game</button>
      </form>
    </div>
  );
};

export default startGame;
