"use client";

import { mdiOpenInNew } from "@mdi/js";
import Icon from "@mdi/react";
import { useState } from "react";
import { Document, Page as PdfPage, pdfjs } from "react-pdf";
import "react-pdf/dist/Page/AnnotationLayer.css";
import "react-pdf/dist/Page/TextLayer.css";

// pdfjs.GlobalWorkerOptions.workerSrc = new URL(
//   "pdfjs-dist/build/pdf.worker.min.mjs",
//   import.meta.url
// ).toString();
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

export function PDF({ url }: { url: string }) {
  const [numPages, setNumPages] = useState<number>(0);
  function onLoadSuccess({ numPages }: { numPages: number }) {
    setNumPages(numPages);
  }

  return (
    <div className="overflow-y-auto h-full">
      <a
        href={url}
        target="_blank"
        rel="noopener noreferrer"
        className="fixed z-10 m-2 p-2 rounded-xl shadow-neutral-300 shadow-xl bg-white opacity-50 hover:opacity-100 transition-opacity duration-200 ease-in-out"
      >
        <Icon path={mdiOpenInNew} size={1.5} className="text-gray-600" />
      </a>
      <Document file={url} onLoadSuccess={onLoadSuccess}>
        {Array.from({ length: numPages }, (_, i) => (
          <PdfPage key={i} pageNumber={i + 1} width={800} />
        ))}
      </Document>
    </div>
  );
}
