import { useEffect, useState } from "react";
import { useParams, useNavigate } 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";

const apiBase = import.meta.env.VITE_API_URL;

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

const TeamAddPlayer = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const [players, setPlayers] = useState<Player[]>([]);
  const [newPlayer, setNewPlayer] = useState({
    name: "",
    nickname: "",
    position: "",
    jersey_number: "",
    age: "",
    favorite_food: "",
    image_url: "",
  });
  const [uploading, setUploading] = useState(false);

  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);
    }
  };

  const handleAddExistingPlayer = async (playerId: number) => {
    try {
      const res = await fetch(`${apiBase}/api/teams/${id}/players`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ playerId }),
      });

      if (res.ok) {
        navigate(`/admin/teams/${id}`);
      } else {
        console.error("Fehler beim Hinzufügen");
      }
    } catch (err) {
      console.error(err);
    }
  };

  const handleCreateNewPlayer = async () => {
    if (!newPlayer.name.trim() || !newPlayer.position.trim()) return;

    try {
      const res = await fetch(`${apiBase}/api/players`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...newPlayer,
          jersey_number: newPlayer.jersey_number ? Number(newPlayer.jersey_number) : null,
          age: newPlayer.age ? Number(newPlayer.age) : null,
          team_ids: [Number(id)],
        }),
      });

      if (res.ok) {
        navigate(`/admin/teams/${id}`);
      } else {
        console.error("Fehler beim Erstellen des Spielers");
      }
    } catch (err) {
      console.error(err);
    }
  };

  const handleImageUpload = async (file: File) => {
    const formData = new FormData();
    formData.append("image", file);
    setUploading(true);

    try {
      const res = await fetch(`${apiBase}/api/upload-player-image`, {
        method: "POST",
        body: formData,
      });

      if (!res.ok) throw new Error("Fehler beim Bild-Upload");

      const data = await res.json();
      setNewPlayer((prev) => ({ ...prev, image_url: data.imageUrl }));
    } catch (err) {
      console.error("Bild-Upload fehlgeschlagen:", err);
    } finally {
      setUploading(false);
    }
  };

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

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

      {/* Bestehende Spieler */}
      <div className="mb-12">
        <h2 className="text-2xl font-bold text-frog-500 mb-4">Bestehende Spieler auswählen</h2>

        {players.length === 0 ? (
          <p className="text-gray-600">Keine Spieler gefunden.</p>
        ) : (
          <div className="grid md:grid-cols-2 gap-6">
            {players.map((player) => (
              <Card key={player.id} className="hover:shadow-md transition-shadow">
                <CardHeader>
                  <CardTitle>
                    {player.name} {player.nickname && `(${player.nickname})`}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-gray-600">Position: {player.position}</p>
                  {player.jersey_number && <p className="text-gray-600">Nr: {player.jersey_number}</p>}
                  <Button
                    className="mt-2 bg-frog-500 hover:bg-frog-600 text-white w-full"
                    onClick={() => handleAddExistingPlayer(player.id)}
                  >
                    Hinzufügen
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Neuen Spieler anlegen */}
      <div>
        <h2 className="text-2xl font-bold text-frog-500 mb-4">Neuen Spieler erstellen</h2>
        <div className="space-y-4">
          <Input
            placeholder="Name *"
            value={newPlayer.name}
            onChange={(e) => setNewPlayer((prev) => ({ ...prev, name: e.target.value }))}
          />
          <Input
            placeholder="Spitzname"
            value={newPlayer.nickname}
            onChange={(e) => setNewPlayer((prev) => ({ ...prev, nickname: e.target.value }))}
          />
          <Input
            placeholder="Position *"
            value={newPlayer.position}
            onChange={(e) => setNewPlayer((prev) => ({ ...prev, position: e.target.value }))}
          />
          <Input
            placeholder="Trikotnummer"
            type="number"
            value={newPlayer.jersey_number}
            onChange={(e) => setNewPlayer((prev) => ({ ...prev, jersey_number: e.target.value }))}
          />
          <Input
            placeholder="Alter"
            type="number"
            value={newPlayer.age}
            onChange={(e) => setNewPlayer((prev) => ({ ...prev, age: e.target.value }))}
          />
          <Input
            placeholder="Lieblingsessen"
            value={newPlayer.favorite_food}
            onChange={(e) => setNewPlayer((prev) => ({ ...prev, favorite_food: e.target.value }))}
          />

          {/* Bild Upload */}
          <Input
            type="file"
            accept="image/*"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) handleImageUpload(file);
            }}
          />
          {uploading && <p className="text-sm text-gray-400">Bild wird hochgeladen...</p>}
          {newPlayer.image_url && (
            <img
              src={`${apiBase}${newPlayer.image_url}`}
              alt="Spielerbild"
              className="mt-2 max-h-40 rounded-md shadow-md"
            />
          )}

          <Button
            onClick={handleCreateNewPlayer}
            className="bg-frog-500 hover:bg-frog-600 text-white w-full"
          >
            Spieler erstellen & hinzufügen
          </Button>
        </div>
      </div>
    </div>
  );
};

export default TeamAddPlayer;
