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

const apiBase = import.meta.env.VITE_API_URL;

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

const TeamList = () => {
  const [teams, setTeams] = useState<Team[]>([]);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [teamToDelete, setTeamToDelete] = useState<Team | null>(null);
  const [confirmInput, setConfirmInput] = useState("");


  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 deleteTeam = async () => {
    if (!teamToDelete) return;
  
    try {
      const res = await fetch(`${apiBase}/api/teams/${teamToDelete.id}`, {
        method: "DELETE",
      });
  
      if (res.ok) {
        setTeams((prev) => prev.filter((t) => t.id !== teamToDelete.id));
        setShowDeleteModal(false);
      } else {
        console.error("Fehler beim Löschen");
      }
    } catch (err) {
      console.error("Fehler:", err);
    }
  };

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

  return (
    <div className="max-w-5xl mx-auto py-12 px-4">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-3xl font-bold text-frog-600">Teams verwalten</h1>
        <Button asChild className="bg-frog-500 hover:bg-frog-600 text-white">
          <Link to="/admin/teams/new">+ Neues Team</Link>
        </Button>
      </div>
  
      <div className="grid md:grid-cols-2 gap-6">
        {teams.map((team) => (
          <Card key={team.id} className="hover:shadow-md transition-shadow">
            <CardHeader>
              <CardTitle className="text-frog-600">{team.name}</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-gray-600">Spieler: {team.player_count}</p>
              <Button
                asChild
                className="mt-4 bg-frog-500 hover:bg-frog-600 text-white"
              >
                <Link to={`/admin/teams/${team.id}`}>Bearbeiten</Link>
              </Button>
              <Button
                variant="destructive"
                className="mt-2"
                onClick={() => {
                  setTeamToDelete(team);
                  setShowDeleteModal(true);
                  setConfirmInput("");
                }}
              >
                Löschen
              </Button>
            </CardContent>
          </Card>
        ))}
      </div>
  
      {/* 🔥 MODAL INS RETURN */}
      {showDeleteModal && teamToDelete && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-6 rounded-lg shadow-lg max-w-md w-full">
            <h2 className="text-xl font-bold text-red-600 mb-4 text-center">
              Team wirklich löschen?
            </h2>
            <p className="mb-2 text-sm text-gray-700 text-center">
              Gib den Teamnamen <strong>"{teamToDelete.name}"</strong> ein, um zu bestätigen:
            </p>
            <input
              type="text"
              value={confirmInput}
              onChange={(e) => setConfirmInput(e.target.value)}
              className="w-full border border-gray-300 rounded-md px-3 py-2 mb-4"
              placeholder="Teamname zur Bestätigung"
            />
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setShowDeleteModal(false)}>
                Abbrechen
              </Button>
              <Button
                variant="destructive"
                onClick={deleteTeam}
                disabled={confirmInput !== teamToDelete.name}
              >
                Löschen
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
  

  
};



export default TeamList;
