import React, { useEffect, useState } from 'react';

import { useNavigate } from 'react-router-dom';
import { getUserFromToken } from '../components/utils/jwt'; // Importiere die Funktion zum Decodieren des Tokens

interface Team {
  id: string;
  name: string;
  players: string[]; // Emails oder Namen
  createdBy: string;
}

const TeamManagement = () => {
  const [teams, setTeams] = useState<Team[]>([]);
  const [name, setName] = useState('');
  const [player2, setPlayer2] = useState('');
  const [error, setError] = useState('');
  const [editingTeam, setEditingTeam] = useState<Team | null>(null);

  const token = localStorage.getItem('token');
  const user = token ? getUserFromToken(token) : null;
  const isAdmin = user?.role === 'admin';

  const fetchTeams = async () => {
    const res = await fetch('/api/teams', {
      headers: { Authorization: `Bearer ${token}` }
    });
    const data = await res.json();
    if (res.ok) setTeams(data.data || []);
    else setError(data.error || 'Fehler beim Laden der Teams');
  };

  useEffect(() => {
    if (token) fetchTeams();
  }, [token]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const body = {
      name,
      players: [user?.email, player2],
    };

    const method = editingTeam ? 'PUT' : 'POST';
    const url = editingTeam ? `/api/teams/${editingTeam.id}` : '/api/teams';

    const res = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(body),
    });

    const data = await res.json();

    if (res.ok) {
      setName('');
      setPlayer2('');
      setEditingTeam(null);
      fetchTeams();
    } else {
      setError(data.error || 'Fehler beim Speichern');
    }
  };

  const handleDelete = async (id: string) => {
    const res = await fetch(`/api/teams/${id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token}` },
    });

    if (res.ok) fetchTeams();
    else setError('Löschen fehlgeschlagen');
  };

  const canEdit = (team: Team) => isAdmin;
  const canDelete = (team: Team) =>
    isAdmin || team.createdBy === user?.userId;

  const canCreate = () => isAdmin || true; // Normale Nutzer dürfen eigene Teams erstellen

  return (
    <div className="max-w-2xl mx-auto p-6 bg-white rounded-xl shadow-md mt-6">
      <h2 className="text-2xl font-bold mb-4">Team Management</h2>
      {error && <p style={{ color: 'red' }}>{error}</p>}

      {canCreate() && (
        <form onSubmit={handleSubmit} className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
          <h3>{editingTeam ? 'Team bearbeiten' : 'Team erstellen'}</h3>
          <input
            className="border p-2 rounded"
            type="text"
            placeholder="Teamname"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />
          
          <input
            className="border p-2 rounded"
            type="email"
            placeholder="E-Mail von Mitspieler"
            value={player2}
            onChange={(e) => setPlayer2(e.target.value)}
            required={!isAdmin}
          />
          <button type="submit"
           className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
          >{editingTeam ? 'Aktualisieren' : 'Erstellen'}</button>
        </form>
      )}

      <hr />
      <h3>Alle Teams</h3>
      <ul>
        {teams.map((team) => (
          <li key={team.id}>
            <strong>{team.name}</strong> – Spieler: {team.players.join(', ')}
            <div style={{ marginTop: '4px' }}>
              {canEdit(team) && (
                <button onClick={() => {
                  setName(team.name);
                  setPlayer2(team.players[1] || '');
                  setEditingTeam(team);
                }}>
                  Bearbeiten
                </button>
              )}
              {canDelete(team) && (
                <button onClick={() => handleDelete(team.id)}>Löschen</button>
              )}
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default TeamManagement;
