import React, {useEffect, useState} from "react";
import {Document, Page} from "react-pdf";
import {pdfjs} from "react-pdf";

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

interface PDFViewerProps {
    url: string;
}

const PDFViewer: React.FC<PDFViewerProps> = ({url}) => {
    const [numPages, setNumPages] = useState(0);

    useEffect(() => {
        const loadPDF = async () => {
            try {
                const loadingTask = pdfjs.getDocument(url);
                const pdf = await loadingTask.promise;
                setNumPages(pdf.numPages);
            } catch (error) {
                console.error("Error loading PDF:", error);
            }
        };

        loadPDF();
    }, [url]);

    return (
        <div className="fm-pdf">
            <Document file={url} onLoadSuccess={({numPages}) => setNumPages(numPages)}>
                {Array.from(new Array(numPages), (el, index) => (
                    <Page key={`page_${index + 1}`} pageNumber={index + 1} />
                ))}
            </Document>
        </div>
    );
};

export default PDFViewer;
