import { useEffect, useRef } from "react";
import type { PdfDocumentProxy } from "@/utils/pdfjsSetup";

interface PdfViewerProps {
  document: PdfDocumentProxy;
  pageNumber: number;
  scale: number;
}

export function PdfViewer({ document, pageNumber, scale }: PdfViewerProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const wrapRef = useRef<HTMLDivElement>(null);
  const renderTaskRef = useRef<{ cancel: () => void } | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function renderPage() {
      if (renderTaskRef.current) {
        renderTaskRef.current.cancel();
        renderTaskRef.current = null;
      }

      const canvas = canvasRef.current;
      if (!canvas) return;

      try {
        const page = await document.getPage(pageNumber);
        if (cancelled) return;

        const viewport = page.getViewport({ scale });
        canvas.width = viewport.width;
        canvas.height = viewport.height;

        const ctx = canvas.getContext("2d");
        if (!ctx) return;

        const renderTask = page.render({ canvasContext: ctx, viewport });
        renderTaskRef.current = renderTask;
        await renderTask.promise;
      } catch {
        /* render failed */
      }
    }

    void renderPage();

    return () => {
      cancelled = true;
      if (renderTaskRef.current) {
        renderTaskRef.current.cancel();
        renderTaskRef.current = null;
      }
    };
  }, [document, pageNumber, scale]);

  return (
    <div ref={wrapRef} className="pdf-page-wrap">
      <canvas ref={canvasRef} className="pdf-page-canvas" />
    </div>
  );
}
