import { FC, useEffect, useState } from 'react';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Typography from '@material-hu/mui/Typography';

import { Document, Page } from 'src/config/react-pdf';

import { usePdfDimensions } from 'src/hooks/usePdfDimensions';
import { getBlobCloudfrontDocument, isSecureFile } from 'src/utils/documents';
import { getBlobUrl } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type PdfDocumentProps = {
  pdfPath: string;
  onLoadError: () => void;
  onLoadSuccess: (param: any) => void;
  pageNumber: number;
};

export const PdfDocument: FC<PdfDocumentProps> = props => {
  const { pdfPath, onLoadError, onLoadSuccess, pageNumber } = props;
  const [blob, setBlob] = useState<string | null>(null);

  const { t } = useLokaliseTranslation('documents');

  const {
    ref: documentRef,
    dimensions: pageDimensions,
    handleLoadPage,
  } = usePdfDimensions({
    fitWidth: true,
  });

  useEffect(() => {
    (async () => {
      if (isSecureFile(pdfPath)) {
        const blobPromise = await getBlobCloudfrontDocument(pdfPath);
        setBlob(getBlobUrl(blobPromise));
      } else {
        setBlob(pdfPath);
      }
    })();
  }, []);

  if (!blob) return null;

  return (
    <Document
      inputRef={documentRef}
      file={blob}
      onLoadError={onLoadError}
      onLoadSuccess={onLoadSuccess}
      loading={
        <Box sx={{ textAlign: 'center' }}>
          <CircularProgress />
        </Box>
      }
      error={
        <Box sx={{ py: 2, width: '100%' }}>
          <Typography
            color="textSecondary"
            variant="subtitle2"
            sx={{ textAlign: 'center' }}
          >
            {t('ERROR_OPEN_PENDING_FILE')}
          </Typography>
        </Box>
      }
    >
      <Page
        renderAnnotationLayer={false}
        pageNumber={pageNumber}
        onLoadSuccess={handleLoadPage}
        width={pageDimensions?.width || 0}
      />
    </Document>
  );
};

export default PdfDocument;
