import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Document, Page, pdfjs } from "react-pdf";
import "react-pdf/dist/Page/AnnotationLayer.css";
import "react-pdf/dist/Page/TextLayer.css";

import type { PDFDocumentProxy } from "pdfjs-dist";
import { LoadingPage } from "./loading";

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

const options = {
	cMapUrl: "/cmaps/",
	standardFontDataUrl: "/standard_fonts/",
	wasmUrl: "/wasm/",
};

export const PDFViewer = ({ url }: { url: string }) => {
	const [numPages, setNumPages] = useState<number>();
	const containerRef = useRef<HTMLDivElement>(null);
	const [width, setWidth] = useState(0);
	const file = useMemo(() => ({ url }), [url]);

	const onResize = useCallback<ResizeObserverCallback>((entries) => {
		const [entry] = entries;

		if (entry) {
			setWidth(entry.contentRect.width);
		}
	}, []);

	const observer = new ResizeObserver(onResize);

	useEffect(() => {
		if (containerRef.current) {
			observer.observe(containerRef.current);
			setWidth(containerRef.current.offsetWidth);
		}
	}, []);

	function onDocumentLoadSuccess({
		numPages: nextNumPages,
	}: PDFDocumentProxy): void {
		setNumPages(nextNumPages);
	}

	return (
		<div
			className="w-full flex justify-center outline mx-1 shadow-lg rounded-md overflow-clip"
			ref={containerRef}
		>
			<Document
				className={"overflow-auto aspect-[1/1.4142]"}
				file={file}
				loading={<LoadingPage />}
				onLoadSuccess={onDocumentLoadSuccess}
				options={options}
			>
				{Array.from(new Array(numPages), (_el, index) => (
					<Page
						key={`page_${index + 1}`}
						pageNumber={index + 1}
						width={width}
					/>
				))}
			</Document>
		</div>
	);
};
