// src/components/FilePreviewModal/PdfPreview.tsx
import React, { useState } from 'react'
import { Document, Page, pdfjs } from 'react-pdf'

// 设置 PDF.js worker
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`

interface PdfPreviewProps {
  src: string
  className?: string
  onLoaded?: () => void
  onError?: (error: any) => void
}

export const PdfPreview: React.FC<PdfPreviewProps> = ({ src, className = '', onLoaded, onError }) => {
  const [numPages, setNumPages] = useState<number | null>(null)
  const [pageNumber, setPageNumber] = useState<number>(1)
  const [containerWidth, setContainerWidth] = useState<number>(800)

  function onDocumentLoadSuccess({ numPages }: { numPages: number }) {
    setNumPages(numPages)
    setPageNumber(1)
    onLoaded?.()
  }

  function changePage(offset: number) {
    setPageNumber(prevPageNumber => prevPageNumber + offset)
  }

  function previousPage() {
    changePage(-1)
  }

  function nextPage() {
    changePage(1)
  }

  return (
    <div className={`${className} flex flex-col h-full`}>
      <div className="flex-grow overflow-auto flex items-center justify-center bg-gray-50 p-2">
        <div
          className="w-full flex justify-center"
          ref={(el) => {
            if (el) {
              setContainerWidth(el.clientWidth)
            }
          }}
        >
          <Document
            file={src}
            onLoadSuccess={onDocumentLoadSuccess}
            onLoadError={onError}
            className="flex flex-col items-center"
          >
            <Page
              pageNumber={pageNumber}
              width={Math.min(containerWidth - 32, 800)} // 减去padding
              className="shadow-md"
            />
          </Document>
        </div>
      </div>
      {numPages !== null && numPages > 1 && (
        <div className="pdf-navigation flex justify-center items-center py-3 bg-white border-t">
          <button
            type="button" // 添加 type 属性
            onClick={previousPage}
            disabled={pageNumber <= 1}
            className="px-3 py-1 mx-1 bg-gray-200 rounded disabled:opacity-50 text-sm"
          >
            上一页
          </button>
          <span className="mx-3 text-sm">
            第
{' '}
{pageNumber}
{' '}
页，共
{' '}
{numPages}
{' '}
页
          </span>
          <button
            type="button" // 添加 type 属性
            onClick={nextPage}
            disabled={pageNumber >= numPages}
            className="px-3 py-1 mx-1 bg-gray-200 rounded disabled:opacity-50 text-sm"
          >
            下一页
          </button>
        </div>
      )}
    </div>
  )
}
