import React, { useEffect, useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import ControlPanel from './ControlPanel';
import { LinearProgress } from '../../loading/LinearProgress';
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
    pdfSection: (props) => ({
        minWidth: props === null || props === void 0 ? void 0 : props.minWidth
    }),
    documentContainer: {
        display: 'flex',
        justifyContent: 'center',
        width: '100%',
        height: '100%',
        overflowX: 'auto',
        overflowY: 'hidden'
    },
    loadingBox: {
        width: '100%'
    }
}));
export const PDFViewer = ({ isPDFOpen = true, fileUrl, blobPDF, closePDF, onClickDownload, minWidth }) => {
    const [scale, setScale] = useState(1.0);
    const [numPages, setNumPages] = useState(null);
    const [pageNumber, setPageNumber] = useState(1);
    const [resolvedFile, setResolvedFile] = useState(null);
    const classes = useStyles({ minWidth });
    useEffect(() => {
        pdfjs.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
    });
    useEffect(() => {
        // Priority: fileUrl > blobPDF > base64 string
        if (fileUrl) {
            setResolvedFile(fileUrl);
            return;
        }
        if (blobPDF instanceof Blob) {
            const url = URL.createObjectURL(blobPDF);
            setResolvedFile(url);
            return () => {
                URL.revokeObjectURL(url);
            };
        }
        // Handle base64 PDF string
        if (typeof blobPDF === 'string' && blobPDF.length > 0) {
            setResolvedFile(`data:application/pdf;base64,${blobPDF}`);
            return;
        }
        setResolvedFile(null);
    }, [fileUrl, blobPDF]);
    function onDocumentLoadSuccess({ numPages }) {
        setNumPages(numPages);
    }
    return (React.createElement("div", null, isPDFOpen && resolvedFile && (React.createElement("div", { id: "pdf-section", className: classes.pdfSection }, React.createElement(ControlPanel, { scale: scale, setScale: setScale, numPages: numPages, pageNumber: pageNumber, setPageNumber: setPageNumber, file: resolvedFile, closePDF: closePDF, onClickDownload: onClickDownload }), React.createElement("div", { className: classes.documentContainer }, React.createElement(Document, { file: resolvedFile, onLoadSuccess: onDocumentLoadSuccess }, React.createElement(Page, { pageNumber: pageNumber, scale: scale, loading: React.createElement("div", { className: classes.loadingBox }, React.createElement(LinearProgress, null)) })))))));
};
//# sourceMappingURL=PDFViewer.js.map