import { useEffect, useState } from "react";
import { useParams, useNavigate, Link } from "react-router-dom";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea";
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 TeamDetail = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const [teamName, setTeamName] = useState("");
  const [liga, setLiga] = useState("");
  const [trainerName, setTrainerName] = useState("");
  const [socialMedia, setSocialMedia] = useState("");
  const [spielerGesucht, setSpielerGesucht] = useState(false);
  const [carouselImages, setCarouselImages] = useState("");
  const [trainingszeiten, setTrainingszeiten] = useState("");
  const [trainingsort, setTrainingsort] = useState("");
  const [kontaktName, setKontaktName] = useState("");
  const [kontaktEmail, setKontaktEmail] = useState("");
  const [teamfarben, setTeamfarben] = useState("");
  const [beschreibung, setBeschreibung] = useState("");
  const [tabellenlink, setTabellenlink] = useState("");
  const [players, setPlayers] = useState<Player[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchTeam = async () => {
    try {
      const res = await fetch(`${apiBase}/api/teams/${id}`);
      const data = await res.json();

      setTeamName(data.name ?? "");
      setLiga(data.liga ?? "");
      setTrainerName(data.trainer_name ?? "");
      setSocialMedia(data.social_media ?? "");
      setSpielerGesucht(data.sucht_spieler ?? false);
      setCarouselImages(data.karussell_bilder ? JSON.stringify(data.karussell_bilder) : "");
      setTrainingszeiten(data.trainingszeiten ?? "");
      setTrainingsort(data.trainingsort ?? "");
      setKontaktName(data.kontakt_name ?? "");
      setKontaktEmail(data.kontakt_email ?? "");
      setTeamfarben(data.teamfarben ?? "");
      setBeschreibung(data.beschreibung ?? "");
      setTabellenlink(data.tabellenlink ?? "");
      setPlayers(data.players ?? []);
    } catch (err) {
      console.error("Fehler beim Laden des Teams:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTeam();
  }, [id]);

  const handleUpdateTeam = async () => {
    try {
      const res = await fetch(`${apiBase}/api/teams/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: teamName,
          liga,
          sucht_spieler: spielerGesucht,
          social_media: socialMedia,
          karussell_bilder: carouselImages ? JSON.parse(carouselImages) : [],
          trainer_name: trainerName,
          trainingszeiten,
          trainingsort,
          kontakt_name: kontaktName,
          kontakt_email: kontaktEmail,
          teamfarben,
          beschreibung,
          tabellenlink,
        }),
      });

      if (!res.ok) throw new Error("Fehler beim Aktualisieren des Teams");

      toast.success("Team erfolgreich aktualisiert!");
      fetchTeam(); // Aktuelle Daten neu laden
    } catch (err) {
      console.error(err);
      toast.error("Fehler beim Aktualisieren des Teams.");
    }
  };

  const handleRemovePlayer = async (playerId: number) => {
    try {
      const res = await fetch(`${apiBase}/api/teams/${id}/players/${playerId}`, {
        method: "DELETE",
      });

      if (res.ok) {
        setPlayers((prev) => prev.filter((p) => p.id !== playerId));
      } else {
        console.error("Fehler beim Entfernen des Spielers");
      }
    } catch (err) {
      console.error(err);
    }
  };

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

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

      <div className="space-y-4 mb-8">
        <Input value={teamName} onChange={(e) => setTeamName(e.target.value)} placeholder="Teamname" />
        <Input value={liga} onChange={(e) => setLiga(e.target.value)} placeholder="Liga" />
        <Input value={trainerName} onChange={(e) => setTrainerName(e.target.value)} placeholder="Trainer/in" />
        <Input value={trainingszeiten} onChange={(e) => setTrainingszeiten(e.target.value)} placeholder="Trainingszeiten" />
        <Input value={trainingsort} onChange={(e) => setTrainingsort(e.target.value)} placeholder="Trainingsort" />
        <Input value={kontaktName} onChange={(e) => setKontaktName(e.target.value)} placeholder="Kontaktname" />
        <Input value={kontaktEmail} onChange={(e) => setKontaktEmail(e.target.value)} placeholder="Kontakt E-Mail" />
        <Input value={teamfarben} onChange={(e) => setTeamfarben(e.target.value)} placeholder="Teamfarben" />
        <Textarea value={beschreibung} onChange={(e) => setBeschreibung(e.target.value)} placeholder="Beschreibung" />
        <Input value={tabellenlink} onChange={(e) => setTabellenlink(e.target.value)} placeholder="Link zur Tabelle" />
        <Input value={socialMedia} onChange={(e) => setSocialMedia(e.target.value)} placeholder="Social Media Link" />

        <div className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={spielerGesucht}
            onChange={() => setSpielerGesucht(!spielerGesucht)}
            className="w-5 h-5 text-frog-500"
          />
          <label className="text-gray-700">Neue Spieler gesucht?</label>
        </div>

        <Textarea
          value={carouselImages}
          onChange={(e) => setCarouselImages(e.target.value)}
          placeholder="Karussell-Bilder (JSON-Array z.B. [\"//uploads/x.jpg\"])"
        />

        <Button onClick={handleUpdateTeam} className="bg-frog-500 hover:bg-frog-600 text-white">
          Team speichern
        </Button>
      </div>

      <div className="mb-8">
        <h2 className="text-2xl font-bold text-frog-500 mb-4">Spieler im Team</h2>

        {players.length === 0 ? (
          <p className="text-gray-600">Noch keine Spieler zugeordnet.</p>
        ) : (
          <div className="grid md:grid-cols-2 gap-6">
            {players.map((player) => (
              <Card key={player.id} className="hover:shadow-md transition-shadow">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle>
                        {player.name} {player.nickname && `(${player.nickname})`}
                      </CardTitle>
                    </div>
                    <div>
                      <img
                        src={player.image_url ? `${apiBase}${player.image_url}` : "/images/default-player.png"}
                        alt={player.name}
                        className="w-16 h-16 object-cover rounded-full border-2 border-frog-500 shadow-sm hover:scale-105 transition-transform"
                      />
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-gray-600">Position: {player.position}</p>
                  {player.jersey_number && (
                    <p className="text-gray-600">Nummer: {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 onClick={() => handleRemovePlayer(player.id)} variant="destructive">
                      Entfernen
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      <div className="text-center mt-8">
        <Button asChild>
          <Link to={`/admin/teams/${id}/add-player`}>
            + Spieler hinzufügen
          </Link>
        </Button>
      </div>
    </div>
  );
};

export default TeamDetail;
