import { useCallback, useEffect, useMemo, useRef, useState } from "react";

import { Document, Page, pdfjs } from "react-pdf";
import { LoadingPage } from "./loading";

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

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);
		}
	}, []);

	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={({ numPages }) => setNumPages(numPages)}
				options={options}
			>
				{Array.from(new Array(numPages), (_el, index) => (
					<Page
						key={`page_${
							// biome-ignore lint/suspicious/noArrayIndexKey: <ok>
							index + 1
						}`}
						pageNumber={index + 1}
						renderAnnotationLayer={false}
						renderTextLayer={false}
						width={width}
					/>
				))}
			</Document>
		</div>
	);
};
