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

import { readToken } from 'helpers'

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

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

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

      try {
        const image = await fetch(String(currentPreviewURL), {
          headers: { Authorization: `Bearer ${readToken()}` },
        }).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)

  // добавление previewImage в зависимость вызывает бесконечный цикл
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPreviewURL])

  return { previewImage }
}
