'use client';

import axios from 'axios';
import Link from 'next/link';
import React, { useEffect, useState } from 'react';
import Lightbox from "yet-another-react-lightbox";
import "yet-another-react-lightbox/styles.css";

interface GalleryImage {
    src: string;
    alt?: string;
    delay?: number;
    year: number;
}

export default function HomePhotoGallerySection() {
    const [galleryImages, setGalleryImages] = useState<GalleryImage[]>([]);
    const [years, setYears] = useState<number[]>([]);
    const [activeYear, setActiveYear] = useState<number | null>(null);
    const [open, setOpen] = useState(false);
    const [currentIndex, setCurrentIndex] = useState(0);

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

    const getEvents = async () => {
        try {
            const eventRes = await axios.get(
                'https://api.tamilculturewaterloo.org/api/events/'
            );

            const eventsData = eventRes?.data?.data || [];

            // Extract images with year (flattened array)
            const formatted = eventsData.map((img: any) => ({
                id: img.id,
                src: img.eventimageurl,
                title: img?.eventtitle || '',
                description: img?.eventdescription || '',
                year: img?.year
            }));

            setGalleryImages(formatted);

            // Unique years, sorted latest first
            const uniqueYears: any = [...new Set(eventsData.map((event: any) => event.year))]

            setYears(uniqueYears);

            // Set latest year as default tab
            if (uniqueYears.length > 0) {
                setActiveYear(uniqueYears[0]);
            }
        } catch (error) {
            console.log("Error fetching event images:", error);
        }
    };

    console.log("activeYear", activeYear)
    console.log("galleryImages", galleryImages)

    // Filter images by active year
    const filteredImages = galleryImages.filter((img) => img.year === activeYear)


    console.log("filteredImages", filteredImages)

    const handleImageClick = (index: number) => {
        const actualIndex = galleryImages.findIndex(
            (img) => img.src === filteredImages[index].src
        );
        setCurrentIndex(actualIndex);
        setOpen(true);
    };

    return (
        <>
            <div className="bloginner-section-area sp4">
                <div className="container">
                    <div className="row">
                        <div className="col-lg-12 m-auto">
                            <div className="event2-header heading5 space-margin60">
                                <h2 className="text-anime-style-3">Photos Gallery</h2>

                                {/* Year Tabs */}
                                <div className="d-flex justify-content-start gap-3 mt-4 flex-wrap">
                                    {years.map((year) => (
                                        <button
                                            key={year}
                                            className={`btn btn-sm gallery-btn ${activeYear === year ? 'btn-primary' : 'btn-outline-primary'
                                                }`}
                                            onClick={() => setActiveYear(year)}
                                        >
                                            {year}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="row gx-5">
                        <div className="col-lg-10">
                            <div className="row mt-4">
                                {filteredImages.slice(0, 8).map((img: any, index) => (
                                    <div
                                        key={index}
                                        className="col-lg-3 col-md-6 mb-4"
                                        data-aos="zoom-in"
                                        data-aos-duration={1000}
                                    >
                                        <div className="blog4-boxarea">
                                            <div
                                                className="img1"
                                                style={{ cursor: 'pointer' }}
                                                onClick={() => handleImageClick(index)}
                                            >
                                                <img
                                                    src={img.src}
                                                    alt={img.alt || `gallery-${index}`}
                                                    loading="lazy"
                                                    style={{ width: '100%', height: 'auto' }}
                                                />
                                                <h3>{img?.eventtitle}</h3>
                                            </div>
                                        </div>
                                    </div>
                                ))}

                                {filteredImages.length === 0 && (
                                    <div className="col-12 text-center mt-5">
                                        <p className="text-muted">
                                            No images found for {activeYear}.
                                        </p>
                                    </div>
                                )}

                                <div
                                    className="btn-area1 text-center"
                                    data-aos="fade-left"
                                    data-aos-duration={1200}
                                >
                                    <Link href="/photo-gallery" className="vl-btn3">
                                        Go To Gallery
                                    </Link>
                                </div>
                            </div>
                        </div>

                        <div className="col-lg-2 ad-banner">
                            <div className="memory-boxarea pl-3">
                                <div
                                    className="img1"
                                    data-aos="zoom-in"
                                    data-aos-duration={1000}
                                >
                                    <img
                                        src="/assets/img/home/ad-banner/photo-gallery-ad.webp"
                                        alt=""
                                        className="mb-5"
                                    />
                                </div>
                            </div>
                        </div>

                        {/* <div className="col-lg-12">
                            <div className="space32" />
                           
                        </div> */}
                    </div>
                </div>
            </div>

            {/* Lightbox */}
            <Lightbox
                open={open}
                close={() => setOpen(false)}
                index={currentIndex}
                slides={galleryImages.map((img) => ({ src: img.src }))}
            />
        </>
    );
}
