import type { PropsWithChildren } from 'react'
import { createContext, useCallback, useContext, useMemo, useState } from 'react'

export type ImageViewerPayload = {
  uri: string
  blurhash?: string
  width?: number
  height?: number
}

type ImageViewerCtx = {
  payload: ImageViewerPayload | null
  open: (p: ImageViewerPayload) => void
  close: () => void
}

const ImageViewerContext = createContext<ImageViewerCtx>({
  payload: null,
  open: () => {
    throw new Error('open called outside of ImageViewerProvider')
  },
  close: () => {},
})

export const ImageViewerProvider = ({ children }: PropsWithChildren) => {
  const [payload, setPayload] = useState<ImageViewerPayload | null>(null)

  const open = useCallback((p: ImageViewerPayload) => {
    setPayload(p)
  }, [])

  const close = useCallback(() => {
    setPayload(null)
  }, [])

  const value = useMemo(() => ({ payload, open, close }), [payload, open, close])

  return <ImageViewerContext value={value}>{children}</ImageViewerContext>
}

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