// src/components/FilePreviewModal/index.tsx
import { Button, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, Spinner } from '@heroui/react'
import { useEffect, useState } from 'react'
import { DocxPreview } from './DocxPreview'
import { ExcelPreview } from './ExcelPreview'
import { PdfPreview } from './PdfPreview'

interface FilePreviewModalProps {
  isOpen: boolean
  onClose: () => void
  doc: any
  docUrl?: string
}

export const FilePreviewModal: React.FC<FilePreviewModalProps> = ({ isOpen, onClose, doc, docUrl }) => {
  const [loading, setLoading] = useState(false)
  const [fileType, setFileType] = useState<string>('')

  // 确定文件类型
  useEffect(() => {
    if (doc?.documentAlias) {
      const name = doc.documentAlias.toLowerCase()
      // 添加更严格的文件类型判断
      if (name.endsWith('.pdf')) {
        setFileType('pdf')
      }
 else if (name.endsWith('.docx')) {
        setFileType('docx')
      }
 else if (name.endsWith('.doc')) {
        setFileType('doc')
      }
 else if (name.endsWith('.xlsx') || name.endsWith('.xls')) {
        setFileType('xlsx')
      }
 else {
        setFileType('')
      }
    }
  }, [doc])

  const handleDownload = () => {
    if (docUrl) {
      const link = document.createElement('a')
      link.href = docUrl
      link.download = doc?.documentAlias || 'document'
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }

  const handleDocumentRendered = () => {
    setLoading(false)
  }

  const handleDocumentError = (error: any) => {
    console.error('文档预览出错:', error)
    setLoading(false)
  }

  const renderPreview = () => {
    if (!docUrl) {
      return (
        <div className="flex flex-col items-center justify-center h-96">
          <p>无法预览该文件</p>
        </div>
      )
    }

    switch (fileType) {
      case 'docx':
        return (
          <div className="h-[70vh] max-h-[70vh] overflow-auto">
            <DocxPreview
              src={docUrl}
              className="w-full min-h-full"
              onRendered={handleDocumentRendered}
              onError={handleDocumentError}
            />
          </div>
        )

      case 'doc':
        return (
          <div className="flex flex-col items-center justify-center h-96">
            <div className="text-center">
              <p className="mb-4">DOC 格式文件无法在线预览</p>
              <div className="flex gap-3 justify-center">
                <Button color="primary" onPress={() => window.open(docUrl, '_blank')} size="sm">
                  在新窗口打开
                </Button>
                <Button color="secondary" onPress={handleDownload} size="sm">
                  下载文件
                </Button>
              </div>
            </div>
          </div>
        )

      case 'xls':
        return (
          <div className="h-[70vh] max-h-[70vh] overflow-auto">
            <ExcelPreview
              src={docUrl}
              options={{ xls: true }}
              className="w-full min-h-full"
              onRendered={handleDocumentRendered}
              onError={handleDocumentError}
            />
          </div>
        )

      case 'xlsx':
        return (
          <div className="h-[70vh] max-h-[70vh] overflow-auto">
            <ExcelPreview
              src={docUrl}
              className="w-full min-h-full"
              onRendered={handleDocumentRendered}
              onError={handleDocumentError}
            />
          </div>
        )

      case 'pdf':
        return (
          <div className="h-[70vh] max-h-[70vh] overflow-auto">
            <PdfPreview
              src={docUrl}
              className="w-full min-h-full"
              onLoaded={handleDocumentRendered}
              onError={handleDocumentError}
            />
          </div>
        )

      default:
        return (
          <div className="flex flex-col items-center justify-center h-96">
            <div className="text-center">
              <p className="mb-4">该文件格式无法在线预览</p>
              <Button color="primary" onPress={() => window.open(docUrl, '_blank')} size="sm">
                在新窗口打开
              </Button>
            </div>
          </div>
        )
    }
  }

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      size="3xl"
      classNames={{
        base: 'max-h-[90vh] max-w-[50vw]',
        body: 'py-4',
        header: 'border-b border-divider',
        footer: 'border-t border-divider',
      }}
    >
      <ModalContent>
        <ModalHeader className="flex items-center justify-between">
          <span className="text-lg font-semibold truncate max-w-md">{doc?.documentAlias || '文件预览'}</span>
        </ModalHeader>
        <ModalBody className="p-0">
          {loading && fileType !== '' && (
            <div className="flex justify-center items-center h-64">
              <Spinner size="lg" />
            </div>
          )}
          {renderPreview()}
        </ModalBody>
        <ModalFooter className="flex justify-end gap-2"></ModalFooter>
      </ModalContent>
    </Modal>
  )
}
