// 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(() => {
    // 重置状态
    setFileType('')

    if (doc?.documentAlias) {
      const name = doc.documentAlias.toLowerCase().trim()

      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')) {
        setFileType('xlsx')
      }
 else if (name.endsWith('.xls')) {
        setFileType('xls')
      }
 else {
        setFileType('')
      }
    }
  }, [doc, isOpen]) // 添加 isOpen 依赖确保每次打开时重新判断

  // 当文件类型或URL变化时重置loading状态
  useEffect(() => {
    if (fileType && docUrl) {
      setLoading(true)
    }
  }, [fileType, docUrl])

  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
              key={docUrl} // 添加key确保组件重新挂载
              src={docUrl}
              className="w-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] flex flex-col">
            <div className="flex-grow overflow-hidden">
              <ExcelPreview
                key={docUrl} // 添加key确保组件重新挂载
                src={docUrl}
                options={{ xls: true }}
                className="h-full"
                onRendered={handleDocumentRendered}
                onError={handleDocumentError}
              />
            </div>
          </div>
        )

      case 'xlsx':
        return (
          <div className="h-[70vh] max-h-[70vh] flex flex-col">
            <div className="flex-grow overflow-hidden">
              <ExcelPreview
                key={docUrl} // 添加key确保组件重新挂载
                src={docUrl}
                className="h-full"
                onRendered={handleDocumentRendered}
                onError={handleDocumentError}
              />
            </div>
          </div>
        )

      case 'pdf':
        return (
          <div className="h-[70vh] max-h-[70vh] overflow-auto">
            <PdfPreview
              key={docUrl} // 添加key确保组件重新挂载
              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>
        )
    }
  }

  // 模态框关闭时重置状态
  const handleClose = () => {
    setLoading(false)
    setFileType('')
    onClose()
  }

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleClose} // 使用改进的关闭函数
      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>
  )
}
