import {
  useEffect,
  useMemo,
  useState,
} from 'react'

export type TUseCardFrontside = {
  preview?: string,
  previewURL?: string,
}

const PREVIEW_WIDTH = 400 // макс. 1920

export const useCardPreview = ({
  preview,
  previewURL,
}: TUseCardFrontside) => {
  const [previewImage, setPreviewImage] = useState('')
  const currentPreviewURL = useMemo(() => (
    previewURL ? `${previewURL}?width=${PREVIEW_WIDTH}` : preview
  ), [preview, previewURL])

  useEffect(() => {
    const controller = new AbortController()
    const { signal } = controller;

    (async () => {
      if (!currentPreviewURL) return

      try {
        const image = await fetch(String(currentPreviewURL), {
          signal,
        })
          .then(async (result) => ({
            blob: await result.blob(),
            status: result.status,
          }))

        if (image.status === 200) {
          setPreviewImage(URL.createObjectURL(image.blob))
        }
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error(e)
      }
    })()

    return () => {
      URL.revokeObjectURL(previewImage)
      controller.abort()
    }
  // добавление previewImage в зависимость вызывает бесконечный цикл
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPreviewURL])

  return { previewImage }
}
