import { PDFContext } from '@cyntler/react-doc-viewer/dist/esm/renderers/pdf/state'
import { setNumPages } from '@cyntler/react-doc-viewer/dist/esm/renderers/pdf/state/actions'
import { initialPDFState } from '@cyntler/react-doc-viewer/dist/esm/renderers/pdf/state/reducer'
import { css } from '@emotion/css'
import { useContext, useEffect } from 'react'
import { Document } from 'react-pdf'
import CenteredSpinner from '../../../components/CenteredSpinner'
import PDFAllPages from './PDFAllPages'
import PDFSinglePage from './PDFSinglePage'

const pdfpage = css`
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
`

const documentComponent = css`
  margin: 0 auto;
`

const PDFPages = () => {
  const {
    state: { mainState, paginated },
    dispatch,
  } = useContext(PDFContext)

  const currentDocument = mainState?.currentDocument || null

  useEffect(() => {
    dispatch(setNumPages(initialPDFState.numPages))
  }, [currentDocument, dispatch])

  if (!currentDocument || currentDocument.fileData === undefined) return null

  return (
    <div className={pdfpage}>
      <Document
        className={documentComponent}
        file={currentDocument.fileData}
        externalLinkTarget='_blank'
        externalLinkRel='noopener noreferrer'
        onLoadSuccess={({ numPages }) => dispatch(setNumPages(numPages))}
        loading={<CenteredSpinner />}
      >
        {paginated ? <PDFSinglePage /> : <PDFAllPages />}
      </Document>
    </div>
  )
}

export default PDFPages
