"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import Link from "next/link";

import Lightbox from "yet-another-react-lightbox";
import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
import Captions from "yet-another-react-lightbox/plugins/captions";
import "yet-another-react-lightbox/styles.css";
import "yet-another-react-lightbox/plugins/thumbnails.css";
import "yet-another-react-lightbox/plugins/captions.css";

import { Skeleton } from '@/components/ui/skeleton';

export default function Gallery() {
  const [galleries, setGalleries] = useState<any[]>([]);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [bgImage, setBgImage] = useState<string>("/images/placeholder.svg");

  useEffect(() => {
    const fetchGalleries = async () => {
      setIsLoading(true);
      try {
        const response = await fetch('/api/gallery-images');
        if (!response.ok) {
          throw new Error(`Error: ${response.statusText}`);
        }
        const data = await response.json();
        setGalleries(data);
      } catch (error) {
        console.error('Failed to fetch galleries:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchGalleries();
  }, []);

  useEffect(() => {
    let intervalId: NodeJS.Timeout;

    if (Array.isArray(galleries) && galleries.length > 0) {
      const validImages = galleries
        .map((h) => h?.image?.trim())
        .filter((img) => img); // filter out empty or undefined images

      if (validImages.length > 1) {
        // Set an initial image
        setBgImage(validImages[Math.floor(Math.random() * validImages.length)]);

        intervalId = setInterval(() => {
          const randomImage =
            validImages[Math.floor(Math.random() * validImages.length)];
          setBgImage(randomImage);
        }, 6000); // change every 3 seconds
      } else {
        // Only one image or none available
        setBgImage(validImages[0] || "/images/placeholder.svg");
      }
    } else {
      setBgImage("/images/placeholder.svg");
    }

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [galleries]);

  return (
    <>
      <style>{`
        .team-hero-bg {
          background-image: linear-gradient(
              to right,
              rgba(0, 70, 173, 0.85),
              rgba(0, 160, 233, 0.85)
            ),
            url(${bgImage});
          background-size: cover;
          background-position: center;
        }
      `}</style>
      <div>
        <section className="team-hero-bg text-white py-20 pt-32">
          <div className="container mx-auto px-4">
            <div className="max-w-3xl">
              <h1 className="text-4xl md:text-5xl font-bold mb-6">
                Our Image Galleries
              </h1>
              <p className="text-xl text-white/90">
                Our gallery offers a glimpse into the vibrant culture of our
                team showcasing moments of collaboration, growth, and community
                impact that reflects our professionalism and values.
              </p>
            </div>
          </div>
        </section>

        <section className="py-16">
          <div className="container mx-auto px-4">
            <div className="mb-12 text-center">
              <p className="text-lg text-gray-600 max-w-3xl mx-auto">
                A visual story of our people and everyday excellence showcasing
                the passion and purpose behind everything we do. Each photo
                reflects our commitment to building a cohesive and dynamic work
                environment.
              </p>
            </div>
            {isLoading ? (
              <div className="grid grid-cols-8 gap-1">
                {Array.from({ length: 16 }).map((_, i) => (
                  <Skeleton key={i} className="h-32 w-full rounded-md" />
                ))}
              </div>
            ) : (
              <div className="grid grid-cols-8 gap-1">
                {galleries.map((gallery, index) => (
                  <div key={gallery.id} className="relative">
                    <img
                      onClick={() => setLightboxIndex(index)}
                      src={gallery.image}
                      alt={gallery.title}
                      className="rounded-md h-32 w-full object-cover"
                    />
                  </div>
                ))}
              </div>
            )}{" "}
            {lightboxIndex !== null && (
              <Lightbox
                open
                index={lightboxIndex}
                close={() => setLightboxIndex(null)}
                slides={galleries.map((img: any) => ({
                  src: img.image,
                  title: img.gallery,
                  description: img.description,
                }))}
                plugins={[Thumbnails, Captions]}
              />
            )}
          </div>
        </section>
      </div>
    </>
  );
}
