import { useHost } from '@inject/graphql/connection/host'
import DocViewerPage from '@inject/shared/components/DocViewer'
import { downloadFileUrl } from '@inject/shared/config'
import authenticatedFetch from '@inject/shared/utils/authenticatedFetch'
import { useEffect, useState, type FC } from 'react'

interface DocViewerComponentProps {
  teamId: string
  fileId: string
  fileName: string
  inInstructor: boolean
  loading?: boolean
  error?: Error
  contentOnly?: boolean
  onBack?: () => void
}

// TODO: clicking on save as, or downloading video through the video player downloads the file with the id as the name
const DocViewerComponent: FC<DocViewerComponentProps> = ({
  teamId,
  fileId,
  fileName,
  inInstructor,
  loading,
  error,
  contentOnly,
  onBack,
}) => {
  const host = useHost()

  const [uri, setUri] = useState<string>('')
  const fileType = fileName.split('.').pop() || 'txt'
  useEffect(() => {
    const downloadUrl = downloadFileUrl(
      host || '',
      teamId,
      fileId,
      inInstructor
    )
    authenticatedFetch(downloadUrl, {
      cache: 'force-cache',
    }).then(async response => {
      let blob = await response.blob()
      // TODO: fix Content-Type on the backend; this is a workaround for SVGs to work
      if (fileType === 'svg') {
        const contentType = 'image/svg+xml'
        blob = new Blob([blob], { type: contentType })
      }
      setUri(window.URL.createObjectURL(blob))
    })
  }, [fileId, fileType, host, inInstructor, teamId])

  return (
    <DocViewerPage
      doc={{
        uri,
        fileName,
        fileType,
      }}
      loading={loading || !uri}
      error={error}
      contentOnly={contentOnly}
      onBack={onBack}
    />
  )
}

export default DocViewerComponent
