import { css } from '@emotion/react'
import { useEffect, useState, type FC } from 'react'
import authenticatedFetch from '../../../utils/authenticatedFetch'
import CenteredSpinner from '../../CenteredSpinner'
import type { RendererProps } from '../types'

const wrapped = css`
  white-space: pre-line;
`

const TextRenderer: FC<RendererProps> = ({ doc }) => {
  const [fileData, setFileData] = useState<string>()
  const [loading, setLoading] = useState<boolean>(true)

  useEffect(() => {
    const fetchData = async () => {
      if (doc?.uri) {
        setLoading(true)
        const response = await authenticatedFetch(doc.uri)
        const text = await response.text()
        setFileData(text)
        setLoading(false)
      }
    }
    fetchData()
  }, [doc?.uri])

  if (loading) return <CenteredSpinner />

  return <div css={wrapped}>{fileData}</div>
}

export default TextRenderer
