import React, { createContext, useContext, useState } from "react";
import Lightbox from "yet-another-react-lightbox";

// Plugins
import Zoom from "yet-another-react-lightbox/plugins/zoom";
import Counter from "yet-another-react-lightbox/plugins/counter";
import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails"; 

// Styles
import "yet-another-react-lightbox/styles.css";
import "yet-another-react-lightbox/plugins/counter.css";
import "yet-another-react-lightbox/plugins/thumbnails.css"; 

const LightboxContext = createContext();

export function LightboxProvider({ children }) {
    const [open, setOpen] = useState(false);
    const [index, setIndex] = useState(0);
    const [slides, setSlides] = useState([]);

    const openLightbox = (images, startIndex = 0) => {
        setSlides(images);
        setIndex(startIndex);
        setOpen(true);
    };

    return (
        <LightboxContext.Provider value={{ openLightbox }}>
            {children}

            <Lightbox
                open={open}
                close={() => setOpen(false)}
                index={index}
                slides={slides}
                
                plugins={[Zoom, Counter, Thumbnails]} 
                
                controller={{ 
                    closeOnPullDown: true, 
                    closeOnPullUp: true,   
                    closeOnBackdropClick: true 
                }}

                styles={{ 
                    container: { 
                        backgroundColor: "rgba(0, 0, 0, 0.95)",
                        zIndex: 9999 
                    },
                    button: { 
                        filter: "drop-shadow(0px 0px 2px rgba(0,0,0,0.8))",
                        transform: "scale(1.2)" 
                    }
                }}

                zoom={{
                    maxZoomPixelRatio: 3,
                    scrollToZoom: true,
                }}

                thumbnails={{
                    position: "bottom",
                    width: 80,
                    height: 50,
                    border: 0,
                    borderRadius: 4,
                    padding: 0,
                    gap: 10,
                    showToggle: true, 
                }}

                carousel={{
                    padding: 0,
                    spacing: 0,
                }}
                
                on={{ view: ({ index: currentIndex }) => setIndex(currentIndex) }}
            />
        </LightboxContext.Provider>
    );
}

export const useLightbox = () => {
    const context = useContext(LightboxContext);
    if (!context) {
        throw new Error("useLightbox must be used within a LightboxProvider");
    }
    return context;
};