import React, { useEffect, useId, useMemo, useState } from 'react'
import { X, QrCode, ShieldCheck } from 'lucide-react'
import { grantDownloadAccess } from '../lib/downloadGate'

type PaymentMethod = 'wechat' | 'alipay'

export type PaymentQrModalProps = {
  open: boolean
  onClose: () => void
  downloadKey: string
  title: string
  amountCny?: number
  qrImageSrc?: string
  onPaid: () => void
}

function getDefaultQrImageSrc(): string {
  // Placeholder SVG kept in public/ so it can be swapped easily later.
  return '/images/placeholder-qr.svg'
}

export const PaymentQrModal: React.FC<PaymentQrModalProps> = ({
  open,
  onClose,
  downloadKey,
  title,
  amountCny = 1,
  qrImageSrc,
  onPaid,
}) => {
  const dialogTitleId = useId()
  const [method, setMethod] = useState<PaymentMethod>('wechat')

  const qrSrc = useMemo(() => qrImageSrc ?? getDefaultQrImageSrc(), [qrImageSrc])

  useEffect(() => {
    if (!open) return
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    window.addEventListener('keydown', onKeyDown)
    return () => window.removeEventListener('keydown', onKeyDown)
  }, [onClose, open])

  if (!open) return null

  return (
    <div className="fixed inset-0 z-[100]">
      <div className="absolute inset-0 bg-black/50" aria-hidden="true" onClick={onClose} />

      <div className="absolute inset-0 flex items-center justify-center p-4">
        <div
          role="dialog"
          aria-modal="true"
          aria-labelledby={dialogTitleId}
          className="w-full max-w-lg rounded-2xl bg-white shadow-xl border border-gray-100 overflow-hidden"
        >
          <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
            <div>
              <div id={dialogTitleId} className="text-base font-semibold text-primary-dark">
                付费下载
              </div>
              <div className="text-xs text-gray-500 mt-1">支付完成后可下载：{title}</div>
            </div>
            <button
              type="button"
              onClick={onClose}
              className="w-9 h-9 inline-flex items-center justify-center rounded-lg text-gray-600 hover:bg-gray-50"
              aria-label="关闭"
            >
              <X size={18} />
            </button>
          </div>

          <div className="px-6 py-5">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <div className="inline-flex items-center gap-2 text-sm text-gray-700">
                <QrCode size={18} className="text-primary" />
                <span>金额：<span className="font-semibold text-primary-dark">{amountCny} 元</span></span>
              </div>
              <div className="inline-flex rounded-xl bg-gray-50 p-1 border border-gray-100">
                <button
                  type="button"
                  onClick={() => setMethod('wechat')}
                  className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                    method === 'wechat' ? 'bg-white text-primary shadow-sm' : 'text-gray-600 hover:text-primary'
                  }`}
                >
                  微信
                </button>
                <button
                  type="button"
                  onClick={() => setMethod('alipay')}
                  className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                    method === 'alipay' ? 'bg-white text-primary shadow-sm' : 'text-gray-600 hover:text-primary'
                  }`}
                >
                  支付宝
                </button>
              </div>
            </div>

            <div className="mt-5 grid sm:grid-cols-[1fr_180px] gap-4 items-start">
              <div className="rounded-2xl bg-background border border-gray-100 p-4">
                <div className="text-sm font-semibold text-primary-dark">扫码支付说明</div>
                <ol className="mt-2 text-sm text-gray-600 space-y-2 list-decimal pl-5">
                  <li>选择微信或支付宝</li>
                  <li>使用对应 App 扫描右侧二维码</li>
                  <li>支付完成后点击“我已付款，继续下载”</li>
                </ol>

                <div className="mt-4 flex items-start gap-2 text-xs text-gray-500">
                  <ShieldCheck size={16} className="mt-0.5 text-accent-dark" />
                  <p>当前为占位二维码。后续替换为正式收款码后即可真实收款。</p>
                </div>
              </div>

              <div className="rounded-2xl border border-gray-100 bg-white p-4">
                <div className="aspect-square rounded-xl overflow-hidden bg-gray-50 border border-gray-100">
                  <img src={qrSrc} alt={`${method === 'wechat' ? '微信' : '支付宝'}收款码`} className="w-full h-full object-contain" />
                </div>
                <div className="mt-3 text-center text-xs text-gray-500">{method === 'wechat' ? '微信扫码' : '支付宝扫码'}</div>
              </div>
            </div>
          </div>

          <div className="px-6 py-4 border-t border-gray-100 flex items-center justify-between gap-3">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-xl text-sm font-medium text-gray-700 hover:bg-gray-50"
            >
              取消
            </button>
            <button
              type="button"
              onClick={() => {
                grantDownloadAccess(downloadKey, method)
                onPaid()
              }}
              className="px-4 py-2 rounded-xl text-sm font-medium text-white bg-primary hover:bg-primary-light"
            >
              我已付款，继续下载
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default PaymentQrModal
