'use client';
import React, { useEffect, useState } from 'react';
import Lightbox from 'yet-another-react-lightbox';
import Captions from 'yet-another-react-lightbox/plugins/captions';
import Zoom from 'yet-another-react-lightbox/plugins/zoom';
import 'yet-another-react-lightbox/styles.css';
import 'yet-another-react-lightbox/plugins/captions.css';
import axios from 'axios';
import { useRouter } from 'next/navigation';
import IconTrashLines from '../icon/icon-trash-lines';
import Swal from 'sweetalert2';
import { buildApiUrl } from '@/utils/BaseUrl.utils';

interface EditEventFormProps {
    eventId: string | null;
}

const ListOfEventsGallery: React.FC<EditEventFormProps> = ({ eventId }) => {
    const router = useRouter();

    const [isOpen, setIsOpen] = useState(false);
    const [photoIndex, setPhotoIndex] = useState(0);
    const [eventImages, setEventImages] = useState<any[]>([]);

    useEffect(() => {
        if (eventId) {
            getEventGallery();
        }
    }, [eventId]);

    const getEventGallery = async () => {
        try {
            const res = await axios.get(buildApiUrl(`event-images/event/${eventId}`));
            const formatted = res.data?.data?.map((img: any) => ({
                id: img.id, // ensure ID is preserved for deletion
                src: img.imageurl,
                title: img?.title || '',
                description: img?.description || '',
            }));
            setEventImages(formatted || []);
        } catch (error) {
            console.log("error", error);
        }
    };

    const showAlert = async (e: React.MouseEvent, item: any) => {
        e.stopPropagation(); // ✅ Prevents triggering the parent onClick (lightbox)

        if (isOpen) setIsOpen(false); // optional: close lightbox if it's open

        Swal.fire({
            icon: 'warning',
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            showCancelButton: true,
            confirmButtonText: 'Delete',
            padding: '2em',
            customClass: { popup: 'sweet-alerts' },
        }).then(async (result) => {
            if (result.isConfirmed) {
                try {
                    await axios.delete(buildApiUrl(`event-images/${item.id}`));
                    Swal.fire({
                        title: 'Deleted!',
                        text: 'Your file has been deleted.',
                        icon: 'success',
                        customClass: { popup: 'sweet-alerts' },
                    });
                    getEventGallery(); // refresh after delete
                } catch (error) {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Failed to delete the file.',
                        icon: 'error',
                        customClass: { popup: 'sweet-alerts' },
                    });
                }
            }
        });
    };

    return (
        <div className="panel">
            <div className='flex justify-between items-center'>
                <h5 className="mb-5 text-lg font-semibold dark:text-white-light">Gallery</h5>
                <button
                    type="button"
                    onClick={() => router.push(`/create-event-gallery?eventid=${eventId}`)}
                    className="bg-blue-600 text-white px-6 py-2 rounded hover:bg-blue-700"
                >
                    Upload Images
                </button>
            </div>

            <div className="mt-10 grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
                {eventImages.map((item, index) => (
                    <div
                        key={item.id}
                        className="cursor-pointer relative"
                        onClick={() => {
                            setPhotoIndex(index);
                            setIsOpen(true);
                        }}
                    >
                        {/* Delete button (top-right corner) */}
                        <div className="absolute top-5 right-5 flex gap-2 z-10">
                            <button
                                onClick={(e) => showAlert(e, item)}
                                className="bg-red-600 text-white text-xs px-2 py-1 rounded"
                            >
                                <IconTrashLines />
                            </button>
                        </div>

                        <img
                            src={item.src}
                            alt={`gallery-${index}`}
                            className="h-full w-full rounded-md object-cover"
                        />
                    </div>
                ))}
            </div>

            <Lightbox
                styles={{ container: { backgroundColor: 'rgba(0,0,0,0.6)' } }}
                open={isOpen}
                close={() => setIsOpen(false)}
                slides={eventImages}
                index={photoIndex}
                plugins={[Captions, Zoom]}
            />
        </div>
    );
};

export default ListOfEventsGallery;
