// src/components/FilePreviewModal/ExcelPreview.tsx
import { useEffect, useState } from 'react'
import * as XLSX from 'xlsx'

interface ExcelPreviewProps {
  src: string
  options?: { xls?: boolean }
  className?: string
  onRendered?: () => void
  onError?: (error: any) => void
}

// 将默认 props 提取为常量
const DEFAULT_OPTIONS = { xls: false }

export const ExcelPreview: React.FC<ExcelPreviewProps> = ({
  src,
  options = DEFAULT_OPTIONS,
  className = '',
  onRendered,
  onError,
}) => {
  const [html, setHtml] = useState<string>('')

  useEffect(() => {
    if (src) {
      fetch(src)
        .then(response => response.arrayBuffer())
        .then((arrayBuffer) => {
          try {
            const workbook = XLSX.read(arrayBuffer, {
              type: 'array',
              cellStyles: true,
              cellHTML: true,
            })

            const firstSheetName = workbook.SheetNames[0]
            const worksheet = workbook.Sheets[firstSheetName]

            // 转换为 HTML 并添加基本样式
            const htmlString = XLSX.utils.sheet_to_html(worksheet, {
              editable: false,
            })

            // 添加基本样式使表格更美观并支持横向滚动
            const styledHtml = htmlString
              .replace('<table', '<table style="width: auto; min-width: 100%; border-collapse: collapse;"')
              .replace(
                /<td/g,
                '<td style="border: 1px solid #d1d5db; padding: 4px 8px; word-wrap: break-word; overflow-wrap: break-word; white-space: nowrap;"',
              )
              .replace(
                /<th/g,
                '<th style="border: 1px solid #d1d5db; padding: 4px 8px; background-color: #f3f4f6; font-weight: bold; word-wrap: break-word; overflow-wrap: break-word; white-space: nowrap;"',
              )

            setHtml(styledHtml)
            onRendered?.()
          }
 catch (error) {
            onError?.(error)
          }
        })
        .catch((error) => {
          onError?.(error)
        })
    }
  }, [src, options, onRendered, onError])

  return (
    <div className={`${className} flex flex-col h-full`}>
      <div className="overflow-auto flex-grow p-4 bg-white">
        <div dangerouslySetInnerHTML={{ __html: html || '<p>无法加载 Excel 内容</p>' }} style={{ minWidth: '100%' }} />
      </div>
    </div>
  )
}
