import { AnchorButton, NonIdealState } from '@blueprintjs/core'
import { useEffect, useRef, type FC } from 'react'
import type { RendererProps } from '../types'

const NotSupportedRenderer: FC<RendererProps> = ({ doc }) => {
  const hasDownloaded = useRef(false)

  useEffect(() => {
    if (!hasDownloaded.current) {
      hasDownloaded.current = true
      const link = document.createElement('a')
      link.href = doc.uri
      link.download = doc.fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }, [doc.fileName, doc.uri])

  return (
    <NonIdealState
      icon='cloud-download'
      title='File type not supported'
      description='Downloading should start automatically. If not, please click the download button below.'
      action={
        <AnchorButton
          icon='download'
          href={doc.uri}
          target='_blank'
          rel='noreferrer'
          intent='primary'
          loading={!doc.uri}
          download={doc.fileName}
        >
          Download
        </AnchorButton>
      }
    />
  )
}

export default NotSupportedRenderer
