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>()
  useEffect(() => {
    const downloadUrl = downloadFileUrl(
      host || '',
      teamId,
      fileId,
      inInstructor
    )
    authenticatedFetch(downloadUrl).then(async response => {
      const blob = await response.blob()
      setUri(window.URL.createObjectURL(blob))
    })
  }, [fileId, host, inInstructor, teamId])

  return (
    <DocViewerPage
      doc={{
        uri: uri || '',
        fileName: fileName,
        fileType: fileName.split('.').pop() || 'txt',
      }}
      loading={loading || !uri}
      error={error}
      contentOnly={contentOnly}
      onBack={onBack}
    />
  )
}

export default DocViewerComponent
