import React, {  useEffect, useState  } from 'react';
import { fetchPlayers,createPlayer,deletePlayer,updatePlayer } from './api';
import { Navigate, useNavigate } from 'react-router-dom';
import { User, UserRole } from '../components/interfaces/users';

// interface Player {
//   id: string;
//   name: string;
//   email: string;
// }

export default function PlayerManagement() {
  const [players, setPlayers] = useState<User[]>([]);
  const [Username, setName] = useState("");
  const [Email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [editingId, setEditingId] = useState<string | null>(null);
  const token = localStorage.getItem('token');
  const navigate = useNavigate();
  
  useEffect(() => {
      if (token) loadPlayers(token);
    }, [token]);


    const loadPlayers = async (token: string) => {
    try {
      const data = await fetchPlayers(token);
      console.log("Geladene Spieler:", data);
      setPlayers(data);
    } catch (error) {
      console.error("Fehler beim Laden der Spieler:", error);
    }
  };
  

  const handleAddOrUpdate = () => {
    if (!Username || !Email) return;

    if (editingId !== null) {
      setPlayers(players.map(p =>
        p.UUID === editingId ? { ...p, Username, Email } : p
      ));
      if (token) {
        // updatePlayer(editingId, { Username, Email }, token);
        throw new Error("Not implemented yet");
      }
      setEditingId(null);
    } else {
      const newPlayer: User = {
        UUID: "",
        Username:"",
        Email: "",
        Role: [UserRole.Player],
        IsActive: true,
      };

      if (token) {
        createPlayer(newPlayer, token);
        setPlayers([...players, newPlayer]);
      }
    }

    setName("");
    setEmail("");
  };

    const handleViewEdit = (playerID: string) => () => {
    navigate(`/players/${playerID}`);
    
  };

  const handleDelete = (id: string) => {
    setPlayers(players.filter(p => p.UUID !== id));
    if (token) {
      deletePlayer(id, token);
    }
    if (editingId === id) {
      setEditingId(null);
      setName("");
      setEmail("");
    }
  };

  return (
    <div className="max-w-2xl mx-auto p-6 bg-white rounded-xl shadow-md mt-6">
      <h1 className="text-2xl font-bold mb-4">🏐 Spielerverwaltung</h1>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
        <input
          type="text"
          placeholder="Spielername"
          value={Username}
          onChange={(e) => setName(e.target.value)}
          className="border p-2 rounded"
        />
        <input
          type="text"
          placeholder="Email"
          value={Email}
          onChange={(e) => setEmail(e.target.value)}
          className="border p-2 rounded"
        />
        <input
          type="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          className="border p-2 rounded"
        />
      </div>

      <button
        onClick={handleAddOrUpdate}
        className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
      >
        {editingId !== null ? "Speichern" : "Hinzufügen"}
      </button>

      <table className="w-full mt-6 table-auto border-collapse">
        <thead>
          <tr className="bg-gray-100 text-left">
            <th className="border px-4 py-2">Name</th>
            <th className="border px-4 py-2">Email</th>
            <th className="border px-4 py-2">Aktionen</th>
          </tr>
        </thead>
        <tbody>
          {players.map(player => (
            <tr key={player.UUID}>
              <td className="border px-4 py-2">{player.Username}</td>
              <td className="border px-4 py-2">{player.Email}</td>
              <td className="border px-4 py-2 space-x-2">
                <button
                    key={player.UUID}
                    onClick={handleViewEdit(player.UUID)}  
                    className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
                  >
                  Bearbeiten
                </button>
                <button
                  onClick={() => handleDelete(player.UUID)}
                  className="bg-red-500 text-white px-2 py-1 rounded"
                >
                  Löschen
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
