import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Card, CardContent, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";

const apiBase = import.meta.env.VITE_API_URL;

type Player = {
  id: number;
  name: string;
  nickname?: string;
  position: string;
  jersey_number?: number;
  image_url?: string;
};

const PlayerManagementPage = () => {
  const [players, setPlayers] = useState<Player[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchPlayers = async () => {
    try {
      const res = await fetch(`${apiBase}/api/players`);
      const data = await res.json();
      setPlayers(data);
    } catch (err) {
      console.error("Fehler beim Laden der Spieler:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPlayers();
  }, []);

  const handleDelete = async (id: number) => {
    if (!confirm("Willst du diesen Spieler wirklich löschen?")) return;

    try {
      const res = await fetch(`${apiBase}/api/players/${id}`, {
        method: "DELETE",
      });

      if (res.ok) {
        setPlayers((prev) => prev.filter((p) => p.id !== id));
        toast.success("Spieler erfolgreich gelöscht!");
      } else {
        toast.error("Fehler beim Löschen des Spielers");
      }
    } catch (err) {
      console.error("Fehler beim Löschen:", err);
      toast.error("Serverfehler");
    }
  };

  if (loading) return <p className="text-center py-12">Lade Spieler...</p>;

  return (
    <div className="max-w-6xl mx-auto py-12 px-4">
      <h1 className="text-3xl font-bold text-frog-600 mb-8">Spieler verwalten</h1>

      {players.length === 0 ? (
        <p className="text-gray-600 text-center">Noch keine Spieler vorhanden.</p>
      ) : (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {players.map((player) => (
            <Card key={player.id} className="hover:shadow-md transition-shadow">
              <CardContent className="flex flex-col items-center p-6">
                <img
                  src={player.image_url ? `${apiBase}${player.image_url}` : "/images/default-player.png"}
                  alt={player.name}
                  className="w-24 h-24 rounded-full object-cover border-2 border-frog-500 shadow-md mb-4"
                />
                <CardTitle className="text-center">
                  {player.name} {player.nickname && `(${player.nickname})`}
                </CardTitle>
                <p className="text-gray-500 text-sm mt-2">{player.position}</p>
                {player.jersey_number && (
                  <p className="text-gray-500 text-sm"># {player.jersey_number}</p>
                )}

                <div className="flex gap-2 mt-4">
                  <Button asChild variant="outline" className="text-frog-600 border-frog-500 hover:bg-frog-50">
                    <Link to={`/admin/players/${player.id}/edit`}>Bearbeiten</Link>
                  </Button>
                  <Button variant="destructive" onClick={() => handleDelete(player.id)}>
                    Löschen
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
};

export default PlayerManagementPage;
