import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, message } from 'antd'
import {
  ArrowLeftOutlined,
  DownloadOutlined,
  ReloadOutlined,
} from '@ant-design/icons'
import './MemberRules.css'

/**
 * 会员管理办法 PDF 文件路径
 * - 文件需放置在 public/member-rules.pdf 下,部署后通过 /member-rules.pdf 访问
 * - 支持通过 url query 覆盖,便于调试: /member-rules?src=https://xxx.pdf
 */
const DEFAULT_PDF_URL = '/member-rules.pdf'

const MemberRules = () => {
  const navigate = useNavigate()
  const [iframeKey, setIframeKey] = useState(0)
  const [iframeError, setIframeError] = useState(false)

  /** 从 URL 参数中读取自定义 PDF 地址(可选) */
  const pdfUrl = useMemo(() => {
    const params = new URLSearchParams(window.location.search)
    return params.get('src') || DEFAULT_PDF_URL
  }, [])

  /** 嵌入预览的 URL: 隐藏工具栏 + 适应宽度 */
  const previewUrl = useMemo(() => {
    // PDF 锚点参数: toolbar=1 显示工具栏, view=FitH 横向铺满
    return `${pdfUrl}#toolbar=1&navpanes=0&view=FitH`
  }, [pdfUrl])

  /** 检测 PDF 是否能正常加载(简单 HEAD 请求) */
  useEffect(() => {
    let cancelled = false
    fetch(pdfUrl, { method: 'HEAD' })
      .then((res) => {
        if (cancelled) return
        if (!res.ok) {
          setIframeError(true)
        }
      })
      .catch(() => {
        if (!cancelled) setIframeError(true)
      })
    return () => {
      cancelled = true
    }
  }, [pdfUrl])

  /** 在浏览器新标签打开 PDF */
  const handleOpenInBrowser = () => {
    window.open(pdfUrl, '_blank', 'noopener,noreferrer')
  }

  /** 下载 PDF */
  const handleDownload = () => {
    try {
      const a = document.createElement('a')
      a.href = pdfUrl
      a.download = '金华市中医药学会会员管理办法.pdf'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    } catch (e) {
      console.error('[下载失败]', e)
      message.error('下载失败,请尝试在浏览器中打开')
    }
  }

  /** 重新加载 iframe */
  const handleReload = () => {
    setIframeError(false)
    setIframeKey((k) => k + 1)
  }

  return (
    <div className="member-rules-page">
      <div className="rules-header">
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          className="back-btn"
        />
        <h1 className="rules-title">会员管理办法</h1>
        <Button
          type="text"
          icon={<ReloadOutlined />}
          onClick={handleReload}
          className="reload-btn"
          aria-label="重新加载"
        />
      </div>

      <div className="rules-toolbar">
        <span className="rules-toolbar-tip">
          如预览异常,请尝试
          <a className="toolbar-link" onClick={handleOpenInBrowser}>
            在浏览器打开
          </a>
          或
          <a className="toolbar-link" onClick={handleDownload}>
            下载查看
          </a>
        </span>
      </div>

      <div className="rules-viewer">
        {iframeError ? (
          <div className="rules-fallback">
            <div className="fallback-icon">📄</div>
            <p className="fallback-title">无法在线预览</p>
            <p className="fallback-desc">
              当前环境暂不支持 PDF 在线预览,请点击下方按钮在浏览器中打开或下载查看。
            </p>
            <div className="fallback-actions">
              <Button type="primary" onClick={handleOpenInBrowser}>
                在浏览器打开
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleDownload}>
                下载 PDF
              </Button>
            </div>
          </div>
        ) : (
          <iframe
            key={iframeKey}
            className="rules-iframe"
            src={previewUrl}
            title="会员管理办法"
            onError={() => setIframeError(true)}
          />
        )}
      </div>

      <div className="rules-actions">
        <Button block onClick={handleOpenInBrowser}>
          在浏览器打开
        </Button>
        <Button
          block
          type="primary"
          icon={<DownloadOutlined />}
          onClick={handleDownload}
        >
          下载 PDF
        </Button>
      </div>
    </div>
  )
}

export default MemberRules
