import React, { useState } from 'react';
import Modal from 'react-modal';
import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import CancelIcon from '@mui/icons-material/Cancel';

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.js',
  import.meta.url
).toString();

const options = {
  cMapUrl: '/cmaps/',
  standardFontDataUrl: '/standard_fonts/',
};

interface Props {
  isOpen: boolean;
  onClose: () => void;
  fileUrl: string;
}

export default function PDFViewerModal({ fileUrl, isOpen, onClose }: Props) {
  const [numPages, setNumPages] = useState<number | null>(null);

  function onDocumentLoadSuccess({ numPages }: { numPages: number }) {
    setNumPages(numPages);
  }

  return (
    <Modal
      isOpen={isOpen}
      onRequestClose={onClose}
      style={{
        overlay: {
          zIndex: 100,
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          padding: '20px',
        },
        content: {
          position: 'relative',
          inset: 'auto',
          width: '100%',
          maxWidth: '900px',
          maxHeight: '90vh',
          backgroundColor: '#001E31',
          border: '1px solid rgba(255, 255, 255, 0.2)',
          borderRadius: '24px',
          padding: '30px 24px 24px',
          overflowY: 'auto',
        },
      }}
    >
      <div className="flex justify-end sticky top-0 z-20 mb-2">
        <CancelIcon
          className="text-white/80 hover:text-[#00AFDD] cursor-pointer transition-colors bg-slate-900/80 rounded-full"
          sx={{ fontSize: 36 }}
          onClick={onClose}
        />
      </div>

      <div className="flex flex-col items-center justify-center w-full">
        <Document
          file={fileUrl}
          onLoadSuccess={onDocumentLoadSuccess}
          options={options}
        >
          {Array.from(new Array(numPages), (el, index) => (
            <div key={`page_${index + 1}`} className="mb-4 shadow-2xl rounded-lg overflow-hidden">
              <Page
                pageNumber={index + 1}
                renderTextLayer={false}
              />
            </div>
          ))}
        </Document>
      </div>
    </Modal>
  );
}
