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

const ImageViewerContext = createContext();

export const ImageViewerProvider = ({ children }) => {
  const [imageViewerProps, setImageViewerProps] = useState(null);

  const showImageViewer = (props) => {
    setImageViewerProps({ ...props, isShow: true });
  };

  const closeImageViewer = () => {
    setImageViewerProps(null);
  };

  const changeImageViewerIndex = (index) => {
    setImageViewerProps((prev) => {
      return { ...prev, index: index };
    });
  };

  return (
    <ImageViewerContext.Provider value={{ showImageViewer }}>
      {children}
      {imageViewerProps && (
        <ImageViewer
          {...imageViewerProps}
          onClose={closeImageViewer}
          onChange={changeImageViewerIndex}
          setImageViewerProps={setImageViewerProps}
        />
      )}
    </ImageViewerContext.Provider>
  );
};

export const useImageViewer = () => useContext(ImageViewerContext);
