// src/pages/GalleryPage.tsx

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

const apiBase = import.meta.env.VITE_API_URL;

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

const GalleryPage = () => {
  const [images, setImages] = useState<GalleryImage[]>([]);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  useEffect(() => {
    const fetchImages = async () => {
      try {
        const res = await fetch(`${apiBase}/api/gallery`);
        const data = await res.json();
        setImages(data);
      } catch (err) {
        console.error("Fehler beim Laden der Galerie:", err);
      }
    };

    fetchImages();
  }, []);

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

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

  return (
    <div className="max-w-7xl mx-auto py-12 px-4">
      <h1 className="text-4xl font-bold text-center text-frog-600 mb-8">
        Bildergalerie 📸
      </h1>

      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
        {images.map((image) => (
          <div
            key={image.id}
            onClick={() => openLightbox(`${apiBase}${image.image_url}`)}
            className="aspect-square overflow-hidden rounded-md shadow-md cursor-pointer transform hover:scale-105 transition-all duration-300"
          >
            <img
              src={`${apiBase}${image.image_url}`}
              alt="Galeriebild"
              className="w-full h-full object-cover"
            />
          </div>
        ))}
      </div>

      {/* Lightbox */}
      {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 rounded-md shadow-lg"
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default GalleryPage;
