import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import { Carousel } from "react-responsive-carousel";
import "react-responsive-carousel/lib/styles/carousel.min.css";
import Skeleton from "react-loading-skeleton";
import "react-loading-skeleton/dist/skeleton.css";

const apiBase = import.meta.env.VITE_API_URL;

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

type Team = {
  id: number;
  name: string;
  liga?: string;
  beschreibung?: string;
  trainingszeiten?: string;
  trainingsort?: string;
  sucht_spieler?: boolean;
  karussell_bilder?: string[];
  players: Player[];
};

const TeamDetailPage = () => {
  const { id } = useParams<{ id: string }>();
  const [team, setTeam] = useState<Team | null>(null);
  const [loading, setLoading] = useState(true);

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

        if (typeof data.karussell_bilder === "string") {
          data.karussell_bilder = JSON.parse(data.karussell_bilder);
        }

        setTeam(data);
      } catch (err) {
        console.error("Fehler beim Laden des Teams:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchTeam();
  }, [id]);

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto py-8 px-4">
        <div className="mb-8">
          <Skeleton height={400} borderRadius={12} />
        </div>

        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-frog-600">
            <Skeleton width={220} />
          </h1>
          <p className="text-lg text-gray-700 mt-2">
            <Skeleton width={160} />
          </p>
          <p className="mt-4 text-gray-600">
            <Skeleton count={2} />
          </p>
          <p className="text-sm text-frog-700 font-medium mt-2">
            <Skeleton width={180} />
          </p>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="bg-white rounded-lg shadow-md p-4">
              <Skeleton height={200} className="mb-4" />
              <Skeleton width={`60%`} height={24} />
              <Skeleton width={`40%`} height={18} />
              <Skeleton width={`50%`} height={14} />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (!team) return <p className="text-center py-12">Team nicht gefunden 🐸</p>;

  return (
    <div className="max-w-7xl mx-auto py-8 px-4">
      {/* Karussell */}
      {team.karussell_bilder && team.karussell_bilder.length > 0 && (
        <div className="mb-8">
          <Carousel
            showThumbs={false}
            showStatus={false}
            infiniteLoop
            autoPlay
            interval={4000}
            className="rounded-lg overflow-hidden"
          >
            {team.karussell_bilder.map((src, index) => (
              <div key={index} className="h-96">
                <img
                  src={`${apiBase}${src}`}
                  alt={`Bild ${index + 1}`}
                  className="w-full h-full object-cover"
                />
              </div>
            ))}
          </Carousel>
        </div>
      )}

      {/* Team Info */}
      <div className="text-center mb-12">
        <h1 className="text-4xl font-bold text-frog-600">{team.name}</h1>
        <p className="text-lg text-gray-700 mt-2">{team.liga}</p>
        <p className="text-gray-600 mt-4">{team.beschreibung}</p>
        <p className="text-sm text-frog-700 font-medium mt-2">
          Training: {team.trainingszeiten || "Nicht angegeben"}
        </p>
        {team.trainingsort && (
          <p className="text-sm text-gray-500 mt-1">
            Ort: {team.trainingsort}
          </p>
        )}
      </div>

      {/* Join Button */}
      {team.sucht_spieler && (
        <div className="mt-6 mb-6 flex justify-center">
          <button className="bg-frog-500 hover:bg-frog-600 text-white font-semibold py-2 px-6 rounded-full shadow-lg transition">
            Mitmachen
          </button>
        </div>
      )}

      {/* Spielerübersicht */}
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6">
        {team.players.map((player) => (
          <div
            key={player.id}
            className="bg-white rounded-lg shadow-md p-4 flex flex-col items-center text-center transform transition duration-300 hover:-translate-y-1 hover:shadow-xl"
          >
            <img
              src={
                player.image_url
                  ? `${apiBase}${player.image_url}`
                  : "/images/default-player.png"
              }
              alt={player.name}
              className="w-full h-108 object-cover rounded-lg mb-4"
            />
            <h3 className="text-xl font-semibold text-frog-700">
              {player.name}
            </h3>
            <p className="text-gray-500">{player.position}</p>
            {player.nickname && (
              <p className="text-sm text-frog-500 mt-1">„{player.nickname}“</p>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

export default TeamDetailPage;
