import React, { useState } from "react";
import { Document, Page, pdfjs } from "react-pdf";

import { Typography } from "@mui/material";

// https://github.com/wojtekmaj/react-pdf?tab=readme-ov-file#copy-worker-to-public-directory
pdfjs.GlobalWorkerOptions.workerSrc =
  process.env.PUBLIC_URL + "/pdf.worker.min.mjs";

interface TermsAndConditionsBoxProps {
  height: string;
  onLoad?: () => void;
}

const TermsAndConditionsBox = ({
  height,
  onLoad,
}: TermsAndConditionsBoxProps) => {
  const [numPages, setNumPages] = useState<number>();

  function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
    setNumPages(numPages);

    if (onLoad) {
      onLoad();
    }
  }

  return (
    <>
      <Typography variant="h4" textAlign="center" gutterBottom>
        Terms and Conditions
      </Typography>
      <div
        style={{
          height: height,
          overflowY: "auto",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <Document
          file={process.env.PUBLIC_URL + "/TermsAndConditions.pdf"}
          onLoadSuccess={onDocumentLoadSuccess}
        >
          {Array.apply(null, Array(numPages))
            .map((x, i) => i + 1)
            .map((page) => {
              return (
                <Page
                  key={page}
                  pageNumber={page}
                  renderTextLayer={false}
                  renderAnnotationLayer={false}
                  width={1070}
                />
              );
            })}
        </Document>
      </div>
    </>
  );
};

export default TermsAndConditionsBox;
