import { useEffect, useRef, useState } from "react";
import type { PDFDocumentProxy } from "pdfjs-dist";
import type { Theme } from "@mui/material/styles";
import { Box, CircularProgress } from "@mui/material";

type PdfPageRendererProps = {
  pdf: PDFDocumentProxy;  
  currentPage: number;
  scale: number;
  theme: { myTheme: Theme };
  styleConfig?: {
    containerStyle?: React.CSSProperties;
  };
};

const PdfPageRenderer: React.FC<PdfPageRendererProps> = ({ pdf, currentPage, scale, theme, styleConfig }) => {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const [isRendering, setIsRendering] = useState(false);

  useEffect(() => {
    let cancelled = false;
    const renderPdf = async () => {
      setIsRendering(true);
      const pdfPage = await pdf.getPage(currentPage);
      if (cancelled) return;
      const viewport = pdfPage.getViewport({ scale });
      const outputScale = window.devicePixelRatio || 1;
      const canvas = canvasRef.current;
      if (!canvas || cancelled) return;

      const context = canvas.getContext("2d");
      if (!context || cancelled) return;

      canvas.width = viewport.width * outputScale;
      canvas.height = viewport.height * outputScale;
      canvas.style.width = `${viewport.width}px`;
      canvas.style.height = `${viewport.height}px`;

      const transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : undefined;

      await pdfPage.render({
        canvasContext: context,
        canvas,
        transform,
        viewport,
      }).promise;
      if (!cancelled) {
        setIsRendering(false);
      }
    };
    renderPdf().catch(() => { if (!cancelled) setIsRendering(false); });
    return () => {
      cancelled = true;
    };
  }, [pdf, currentPage, scale]);

  return (
    <Box sx={{ position: "relative", display: "inline-block", lineHeight: 0 }}>
      <canvas
        ref={canvasRef}
        style={{
          display: "block",
          borderRadius: "8px",
          border: `1px solid ${theme?.myTheme?.palette?.primary?.light}`,
          ...styleConfig?.containerStyle,
        }}
      />
      {isRendering && (
        <Box
          sx={{
            position: "absolute",
            inset: 0,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            borderRadius: "8px",
            backgroundColor: "rgba(255, 255, 255, 0.65)",
            backdropFilter: "blur(2px)",
            zIndex: 10,
          }}
          role="status"
          aria-label="Rendering page"
        >
          <CircularProgress size={32} thickness={4} />
        </Box>
      )}
    </Box>
  );
};

export default PdfPageRenderer;