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

const NewTournament = () => {
  const navigate = useNavigate();
  const token = localStorage.getItem('token')|| '';

  const [name, setName] = useState('');
  const [location, setLocation] = useState('');
  const [date, setDate] = useState('');
  const [maxTeams, setMaxTeams] = useState(8);
  const [message, setMessage] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const data = JSON.stringify({ name, location, date, maxTeams });

    const res = await createTournament(data, token);
    // const data = await res.json();

    if (res.ok) {
      setMessage('Turnier erfolgreich erstellt.');
      setTimeout(() => navigate('/tournaments'), 1500);
    } else {
      setMessage('Fehler beim Erstellen.');
    }
  };

  return (
    <div className="max-w-xl mx-auto mt-8 p-6 bg-white shadow-md rounded-md">
      <h2 className="text-2xl font-semibold mb-6">Neues Turnier erstellen</h2>
      <form className="space-y-4" onSubmit={handleSubmit}>
        <div>
          <label className="block font-medium mb-1">Turniername</label>
          <input
            type="text"
            className="w-full border border-gray-300 p-2 rounded"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />
        </div>

        <div>
          <label className="block font-medium mb-1">Ort</label>
          <input
            type="text"
            className="w-full border border-gray-300 p-2 rounded"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
            required
          />
        </div>

        <div>
          <label className="block font-medium mb-1">Datum</label>
          <input
            type="date"
            className="w-full border border-gray-300 p-2 rounded"
            value={date}
            onChange={(e) => setDate(e.target.value)}
            required
          />
        </div>

        <div>
          <label className="block font-medium mb-1">Maximale Teams</label>
          <input
            type="number"
            className="w-full border border-gray-300 p-2 rounded"
            value={maxTeams}
            onChange={(e) => setMaxTeams(Number(e.target.value))}
            min={2}
            max={64}
          />
        </div>

        <button
          type="submit"
          className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
        >
          Erstellen
        </button>

        {message && <p className="text-green-600 font-medium mt-2">{message}</p>}
      </form>
    </div>
  );
};

export default NewTournament;
