import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import { Link } from "react-router-dom";

const apiBase = import.meta.env.VITE_API_URL;

type GalleryImage = {
  id: number;
  image_url: string;
};

type AnimatedImage = GalleryImage & { fading?: boolean };

const GallerySection = () => {
  const [allImages, setAllImages] = useState<GalleryImage[]>([]);
  const [displayImages, setDisplayImages] = useState<AnimatedImage[]>([]);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  useEffect(() => {
    const fetchImages = async () => {
      try {
        const res = await fetch(`${apiBase}/api/gallery`);
        const data = await res.json();
        setAllImages(data);

        const shuffled = [...data].sort(() => 0.5 - Math.random());
        setDisplayImages(shuffled.slice(0, 6));
      } catch (err) {
        console.error("Fehler beim Laden der Galerie:", err);
      }
    };

    fetchImages();
  }, []);

  // Bild zufällig austauschen mit Animation
  useEffect(() => {
    const interval = setInterval(() => {
      if (allImages.length <= 6) return;

      setDisplayImages((prev) => {
        const currentIds = prev.map((img) => img.id);
        const remaining = allImages.filter((img) => !currentIds.includes(img.id));
        if (remaining.length === 0) return prev;

        const newImage = remaining[Math.floor(Math.random() * remaining.length)];
        const indexToReplace = Math.floor(Math.random() * prev.length);

        const updated = [...prev];
        updated[indexToReplace] = { ...updated[indexToReplace], fading: true };

        setTimeout(() => {
          updated[indexToReplace] = { ...newImage, fading: false };
          setDisplayImages([...updated]);
        }, 400); // passt zur fade-out duration

        return [...updated];
      });
    }, 5000);

    return () => clearInterval(interval);
  }, [allImages]);

  const openLightbox = (image: string) => {
    setSelectedImage(image);
    document.body.style.overflow = "hidden";
  };

  const closeLightbox = () => {
    setSelectedImage(null);
    document.body.style.overflow = "auto";
  };

  return (
    <section id="gallery" className="py-16 bg-gray-50">
      <style>
        {`
          .fade-img {
            transition: opacity 0.4s ease, transform 0.4s ease;
          }

          .fade-out {
            opacity: 0;
            transform: scale(0.95);
          }

          .fade-in {
            opacity: 1;
            transform: scale(1);
          }

          .gallery-tile {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
          }

          .gallery-tile:hover {
            transform: scale(1.03);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
          }
        `}
      </style>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h2 className="text-3xl font-bold text-gray-900">Galerie</h2>
          <p className="mt-4 text-xl text-gray-600">Eindrücke aus unserem Vereinsleben</p>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
          {displayImages.map((image) => (
            <div
              key={image.id}
              className="aspect-square overflow-hidden rounded-lg cursor-pointer gallery-tile"
              onClick={() => openLightbox(`${apiBase}${image.image_url}`)}
            >
              <img
                src={`${apiBase}${image.image_url}`}
                alt="Galeriebild"
                className={`w-full h-full object-cover fade-img ${
                  image.fading ? "fade-out" : "fade-in"
                }`}
              />
            </div>
          ))}
        </div>

        <div className="mt-12 flex justify-center">
          <Link to="/gallery">
            <Button className="bg-frog-500 hover:bg-frog-600">
              Mehr Bilder anzeigen
            </Button>
          </Link>
      </div>

      </div>

      {selectedImage && (
        <div
          className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center"
          onClick={closeLightbox}
        >
          <Button
            variant="ghost"
            size="icon"
            className="absolute top-4 right-4 text-white hover:bg-white/10"
            onClick={(e) => {
              e.stopPropagation();
              closeLightbox();
            }}
          >
            <X className="h-8 w-8" />
          </Button>

          <div
            className="relative max-w-4xl max-h-[80vh]"
            onClick={(e) => e.stopPropagation()}
          >
            <img
              src={selectedImage}
              alt="Vergrößertes Bild"
              className="max-w-full max-h-[80vh] object-contain"
            />
          </div>
        </div>
      )}
    </section>
  );
};

export default GallerySection;
