import { createContext, useState } from "react";
import { ImageViewer } from "./ImageViewer";

interface ImageViewerProviderProps {
    children: React.ReactNode;
}

export interface ImageToView {
    src: string;
    caption?: string;
    timestamp?: number;
}

export interface ImageViewerContextType {
    open: (images: ImageToView[], startIndex: number) => void;
    close: () => void;
}

export const ImageViewerContext = createContext<ImageViewerContextType|null>(null);

export function ImageViwerProvider(props : ImageViewerProviderProps) {

    const [imagesToView, setImagesToView] = useState<ImageToView[]>([]);
    const [currentSlide, setCurrentSlide] = useState<number>(0);

    const open = (images: ImageToView[], startIndex: number) => {
        setImagesToView(images);
        setCurrentSlide(startIndex);
    };

    const close = () => {
        setImagesToView([]);
        setCurrentSlide(0);
    };

    return (
        <ImageViewerContext.Provider value={{
            open,
            close
        }}>
            {props.children}
            {imagesToView.length > 0 && 
                <ImageViewer 
                    images={imagesToView} 
                    initialSlide={currentSlide} 
                    onClose={close} 
                />
            }
        </ImageViewerContext.Provider>
    );
}