import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";

const apiBase = import.meta.env.VITE_API_URL;

const TeamCreate = () => {
  const [teamName, setTeamName] = useState("");
  const [liga, setLiga] = useState("");
  const [suchtSpieler, setSuchtSpieler] = useState(false);
  const [socialMedia, setSocialMedia] = useState("");
  const [trainerName, setTrainerName] = useState("");
  const [carouselImages, setCarouselImages] = useState<string>("");
  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 [saving, setSaving] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");

  const navigate = useNavigate();

  const handleSave = async () => {
    if (!teamName.trim()) return;

    setSaving(true);
    setErrorMsg("");

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

      if (!res.ok) {
        const msg = await res.text();
        setErrorMsg(msg);
        throw new Error(msg);
      }

      navigate("/admin/teams");
    } catch (err) {
      console.error(err);
    } finally {
      setSaving(false);
    }
  };

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

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

        <div className="flex items-center gap-2">
          <input
            id="suchtSpieler"
            type="checkbox"
            checked={suchtSpieler}
            onChange={(e) => setSuchtSpieler(e.target.checked)}
          />
          <Label htmlFor="suchtSpieler">Spieler/in gesucht?</Label>
        </div>

        <div>
          <Label htmlFor="carouselImages">Karussell-Bilder (als JSON-Array)</Label>
          <Textarea
            id="carouselImages"
            placeholder='z. B. ["/uploads/x.jpg", "/uploads/y.jpg"]'
            value={carouselImages}
            onChange={(e) => setCarouselImages(e.target.value)}
          />
        </div>

        {errorMsg && (
          <p className="text-sm text-red-600 bg-red-50 border border-red-200 px-3 py-2 rounded-md">
            {errorMsg}
          </p>
        )}

        <Button
          onClick={handleSave}
          disabled={saving}
          className="bg-frog-500 hover:bg-frog-600 text-white"
        >
          {saving ? "Speichern..." : "Speichern"}
        </Button>
      </div>
    </div>
  );
};

export default TeamCreate;
