import { Document, Page, pdfjs } from "react-pdf";
import { useState } from 'react';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import { Box, IconButton } from '@mui/material';
import ArrowCircleLeftIcon from '@mui/icons-material/ArrowCircleLeft';
import ArrowCircleRightIcon from '@mui/icons-material/ArrowCircleRight';
import testPDF from '/example.pdf';

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
    "pdfjs-dist/build/pdf.worker.min.mjs",
    import.meta.url,
).toString();

export default function PDFViewer() {
    const [numPages, setNumPages] = useState<number | null>(null);
    const [pageNumber, setPageNumber] = useState(1);

    const onDocumentLoadSuccess = ({ numPages }: { numPages: number }) => {
        setNumPages(numPages);
    };

    return (
        <Box
            display="flex"
            flexDirection="column"
            justifyContent="center"
            alignItems="center"
            width="100%"
            height="100%"
            p={2}
        >
            <Box
                sx={{
                    height: '90%',
                    overflow: 'auto',
                    display: 'flex',
                    justifyContent: 'center',
                }}
            >
                <Document file={testPDF} onLoadSuccess={onDocumentLoadSuccess}>
                    <Page
                        pageNumber={pageNumber}
                        scale={0.9}
                    />
                </Document>
            </Box>
            <Box
                mt={2}
                display="flex"
                alignItems="center"
                justifyContent="center"
                gap={1}
            >
                <IconButton disabled={pageNumber <= 1} onClick={() => setPageNumber(p => p - 1)}>
                    <ArrowCircleLeftIcon fontSize="large" />
                </IconButton>
                <span>{pageNumber} / {numPages}</span>
                <IconButton
                    disabled={pageNumber >= (numPages || 1)}
                    onClick={() => setPageNumber(p => p + 1)}
                >
                    <ArrowCircleRightIcon fontSize="large" />
                </IconButton>
            </Box>
        </Box>
    );
}