import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Document, Page } 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";

import "pdfjs-dist/build/pdf.worker.min.mjs";

//pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

// 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="mx-1 flex w-full justify-center overflow-clip rounded-md shadow-lg outline"
			ref={containerRef}
		>
			<Document
				className={"aspect-[1/1.4142] overflow-auto"}
				file={file}
				loading={<LoadingPage />}
				noData={
					"Errore nel caricare il documento, riprova più tardi o Scaricalo"
				}
				onLoadSuccess={onDocumentLoadSuccess}
				options={options}
			>
				{Array.from(new Array(numPages), (_el, index) => (
					<Page
						key={`page_${index + 1}`}
						pageNumber={index + 1}
						width={width}
					/>
				))}
			</Document>
		</div>
	);
};
