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 { useToast } from "@/components/ui/use-toast";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

const apiBase = import.meta.env.VITE_API_URL;

type Team = {
  id: number;
  name: string;
};

const PlayerEdit = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { toast } = useToast();

  const [name, setName] = useState("");
  const [nickname, setNickname] = useState("");
  const [position, setPosition] = useState("");
  const [jerseyNumber, setJerseyNumber] = useState<number | undefined>();
  const [birthdate, setBirthdate] = useState("");
  const [favoriteFood, setFavoriteFood] = useState("");
  const [status, setStatus] = useState("aktiv");
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);

  const [teams, setTeams] = useState<Team[]>([]);
  const [selectedTeamId, setSelectedTeamId] = useState<number | null>(null);

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

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

      setName(data.name || "");
      setNickname(data.nickname || "");
      setPosition(data.position || "");
      setJerseyNumber(data.jersey_number || undefined);
      setBirthdate(data.birthdate ? data.birthdate.substring(0, 10) : "");
      setFavoriteFood(data.favorite_food || "");
      setStatus(data.status || "aktiv");
      setImageUrl(data.image_url ? `${apiBase}${data.image_url}` : null);
      if (data.team_ids && data.team_ids.length > 0) {
        setSelectedTeamId(data.team_ids[0]);
      }
    } catch (err) {
      console.error("Fehler beim Laden des Spielers:", err);
    }
  };

  const fetchTeams = async () => {
    try {
      const res = await fetch(`${apiBase}/api/teams`);
      const data = await res.json();
      setTeams(data);
    } catch (err) {
      console.error("Fehler beim Laden der Teams:", 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 Hochladen des Bildes");

      const data = await res.json();
      setImageUrl(`${apiBase}${data.imageUrl}`);
    } catch (err) {
      console.error(err);
    } finally {
      setUploading(false);
    }
  };

  const handleSave = async () => {
    try {
      // Spieler speichern
      const res = await fetch(`${apiBase}/api/players/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          nickname,
          position,
          jersey_number: jerseyNumber,
          birthdate,
          favorite_food: favoriteFood,
          status,
          image_url: imageUrl?.replace(apiBase, ""),
        }),
      });

      if (!res.ok) throw new Error("Fehler beim Speichern");

      // Teamzuordnung aktualisieren
      if (selectedTeamId) {
        await fetch(`${apiBase}/api/players/${id}/assign-team`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ team_id: selectedTeamId }),
        });
      }

      toast({
        title: "Spieler gespeichert",
        description: "Die Änderungen wurden erfolgreich übernommen.",
      });

      setTimeout(() => {
        navigate(-1);
      }, 500);
    } catch (err) {
      console.error("Fehler beim Speichern:", err);
    }
  };

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

      <div className="space-y-4">
        <Input placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
        <Input placeholder="Spitzname" value={nickname} onChange={(e) => setNickname(e.target.value)} />
        <Input placeholder="Position" value={position} onChange={(e) => setPosition(e.target.value)} />
        <Input
          type="number"
          placeholder="Trikotnummer"
          value={jerseyNumber || ""}
          onChange={(e) => setJerseyNumber(Number(e.target.value))}
        />
        <Input
          type="date"
          placeholder="Geburtstag"
          value={birthdate}
          onChange={(e) => setBirthdate(e.target.value)}
        />
        <Input
          placeholder="Lieblingsessen"
          value={favoriteFood}
          onChange={(e) => setFavoriteFood(e.target.value)}
        />
        <Input
          placeholder="Status (aktiv, verletzt, pausiert)"
          value={status}
          onChange={(e) => setStatus(e.target.value)}
        />

        {/* Team Auswahl */}
        <div>
          <Label>Teamzugehörigkeit</Label>
          <Select
            value={selectedTeamId?.toString()}
            onValueChange={(value) => setSelectedTeamId(Number(value))}
          >
            <SelectTrigger>
              <SelectValue placeholder="Team auswählen" />
            </SelectTrigger>
            <SelectContent>
              {teams.map((team) => (
                <SelectItem key={team.id} value={team.id.toString()}>
                  {team.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* 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>}
        {imageUrl && (
          <img
            src={imageUrl}
            alt="Spielerbild"
            className="mt-2 max-h-40 rounded-md object-cover shadow-md"
          />
        )}

        {/* Buttons */}
        <div className="flex justify-end gap-4 mt-6">
          <Button variant="outline" asChild>
            <Link to="/admin/players">Abbrechen</Link>
          </Button>
          <Button onClick={handleSave} className="bg-frog-500 hover:bg-frog-600 text-white">
            Speichern
          </Button>
        </div>
      </div>
    </div>
  );
};

export default PlayerEdit;
