import { useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { fetchTournament, updateTournament, registerTeam } from './api';
import { useAuth } from './AuthContext';

import { Tournament } from '../components/interfaces/types';

export default function TournamentDetails() {
  const { id } = useParams<{ id: string }>();
  const { token, userId } = useAuth();
  const [tournament, setTournament] = useState<Tournament | null>(null);
  const [editMode, setEditMode] = useState(false);
  const [formData, setFormData] = useState({ name: '', location: '', maxParticipants: 0 });
  const [teamName, setTeamName] = useState('');
  const [error, setError] = useState<string | null>(null);


  useEffect(() => {
    if (!id) return;
    fetchTournament(id, token ?? undefined)
      .then((data) => {
        setTournament(data);
        setFormData({
          name: data.name,
          location: data.location,
          maxParticipants: data.maxParticipants,
        });
      })
      .catch(() => setError('Fehler beim Laden'));
  }, [id, token]);

  if (!tournament) return <p className="p-6">Lade Turnier…</p>;

  const isOwner = userId === tournament.organizerId;

  async function saveChanges() {
    if (!token || !tournament) return;
    try {
      await updateTournament(tournament.id, formData, token);
      setTournament({ ...tournament, ...formData });
      setEditMode(false);
      setError(null);
    } catch {
      setError('Speichern fehlgeschlagen');
    }
  }

  async function handleRegisterTeam() {
    if (!token) {
      setError('Bitte einloggen, um Teams anzumelden');
      return;
    }
    if (!teamName.trim()) return;
    if (!tournament) return;

    try {
      await registerTeam(tournament.id, { name: teamName }, token);
      setTournament({
        ...tournament,
        teams: [...tournament.teams, { id: Math.random().toString(), name: teamName }],
      });
      setTeamName('');
      setError(null);
    } catch {
      setError('Anmeldung fehlgeschlagen');
    }
  }

  return (
    <div className="p-6 max-w-3xl mx-auto">
      <h2 className="text-2xl font-bold mb-4">Turnierdetails</h2>

      {error && <p className="text-red-600 mb-4">{error}</p>}

      {editMode ? (
        <>
          <input
            className="border p-2 w-full mb-3 rounded"
            value={formData.name}
            onChange={e => setFormData({ ...formData, name: e.target.value })}
            placeholder="Name"
          />
          <input
            className="border p-2 w-full mb-3 rounded"
            value={formData.location}
            onChange={e => setFormData({ ...formData, location: e.target.value })}
            placeholder="Ort"
          />
          <input
            type="number"
            className="border p-2 w-full mb-3 rounded"
            value={formData.maxParticipants}
            onChange={e => setFormData({ ...formData, maxParticipants: parseInt(e.target.value) || 0 })}
            placeholder="Max. Teilnehmer"
          />
          <button onClick={saveChanges} className="bg-blue-600 text-white px-4 py-2 rounded mr-2">
            Speichern
          </button>
          <button onClick={() => setEditMode(false)} className="bg-gray-400 text-white px-4 py-2 rounded">
            Abbrechen
          </button>
        </>
      ) : (
        <>
          <p><strong>Name:</strong> {tournament.name}</p>
          <p><strong>Ort:</strong> {tournament.location}</p>
          <p><strong>Teilnehmer:</strong> {tournament.teams.length} / {tournament.maxParticipants}</p>

          {isOwner && (
            <button onClick={() => setEditMode(true)} className="mt-4 bg-yellow-500 text-white px-4 py-2 rounded">
              Turnier bearbeiten
            </button>
          )}

          <h3 className="mt-8 text-xl font-semibold">Angemeldete Teams</h3>
          <ul className="list-disc pl-6 mt-2">
            {tournament.teams.map(team => (
              <li key={team.id}>{team.name}</li>
            ))}
          </ul>

          {token && tournament.teams.length < tournament.maxParticipants && (
            <div className="mt-6">
              <input
                className="border p-2 rounded mr-2"
                placeholder="Teamname"
                value={teamName}
                onChange={e => setTeamName(e.target.value)}
              />
              <button onClick={handleRegisterTeam} className="bg-green-600 text-white px-3 py-1 rounded">
                Team anmelden
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
