// src/components/FilePreviewModal/DocxPreview.tsx
import React, { useEffect, useRef } from 'react'
import { renderAsync } from 'docx-preview'

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

export const DocxPreview: React.FC<DocxPreviewProps> = ({ src, className = '', onRendered, onError }) => {
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (src && containerRef.current) {
      fetch(src)
        .then(response => response.arrayBuffer())
        .then((arrayBuffer) => {
          const blob = new Blob([arrayBuffer], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          })

          // 清空容器
          if (containerRef.current) {
            containerRef.current.innerHTML = ''
          }

          return renderAsync(blob, containerRef.current!, undefined, {
            className,
            inWrapper: true,
            breakPages: true,
            ignoreWidth: false,
            ignoreHeight: false,
            ignoreFonts: false,
          })
        })
        .then(() => {
          onRendered?.()
        })
        .catch((error) => {
          console.error('DOCX 渲染失败:', error)
          onError?.(error)
        })
    }
  }, [src, className, onRendered, onError])

  return (
    <div
      ref={containerRef}
      className={className}
      style={{
        overflow: 'auto',
        height: '100%',
        padding: '1rem',
        backgroundColor: '#fff',
        maxWidth: '100%',
        boxSizing: 'border-box',
      }}
    />
  )
}
