import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { getUserFromToken } from '../components/utils/jwt'; // Importiere die Funktion zum Decodieren des Tokens
import {fetchPlayer} from './api'; // Importiere die Funktion zum Abrufen des Spielers
import { User } from '../components/interfaces/users';


const ViewEditPlayer = () => {
  const { id } = useParams<{ id: string }>();
  const token = localStorage.getItem('token');
  const currentUser = token ? getUserFromToken(token) : null;
  const isAdmin = currentUser?.role?.includes('admin');

  const [player, setPlayer] = useState<User | null>(null);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [role, setRole] = useState('');
  const [message, setMessage] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      if (!token || !id) {
        setMessage('Token oder Spieler-ID fehlt.');
        return;
      }
      try {
        const data = await fetchPlayer(token, id);
        console.log("Geladener Spieler:", data);
        setPlayer(data);
        setName(data.Username);
        setEmail(data.Email);
        setRole(data.Roles);
      } catch (error) {
        setMessage('Spieler konnte nicht geladen werden.');
      }
    };

    fetchData();
  }, [id, token]);

  const handleSave = async () => {
    const res = await fetch(`/api/players/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({ name, email, role }),
    });

    if (res.ok) {
      setMessage('Spieler wurde aktualisiert.');
    } else {
      setMessage('Fehler beim Speichern.');
    }
  };

  if (!player) return <p className="text-center mt-10">Lade Spieler...</p>;

  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-4">Spielerprofil</h2>

      <div className="space-y-4">
        <div>
          <label className="block font-medium mb-1">Name</label>
          {isAdmin ? (
            <input
              type="text"
              className="w-full border border-gray-300 p-2 rounded-md"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          ) : (
            <p>{player.Username}</p>
          )}
        </div>

        <div>
          <label className="block font-medium mb-1">E-Mail</label>
          {isAdmin ? (
            <input
              type="email"
              className="w-full border border-gray-300 p-2 rounded-md"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          ) : (
            <p>{player.Email}</p>
          )}
        </div>

        <div>
          <label className="block font-medium mb-1">Rolle</label>
          {isAdmin ? (
            <select
              className="w-full border border-gray-300 p-2 rounded-md"
              value={role}
              onChange={(e) => setRole(e.target.value)}
            >
              <option value="user">User</option>
              <option value="admin">Admin</option>
            </select>
          ) : (
            <p>{player.Role}</p>
          )}
        </div>

        {isAdmin && (
          <button
            className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700"
            onClick={handleSave}
          >
            Speichern
          </button>
        )}

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

export default ViewEditPlayer;
