import { useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { Button, Card, message, Modal } from 'antd'
import { ArrowLeftOutlined, GlobalOutlined } from '@ant-design/icons'
import {
  createRechargeAlipayH5Order,
  type RechargeAlipayH5OrderResult,
} from '../api/payment'
import './Payment.css'

/**
 * 测试阶段调起支付宝的金额(元)
 * 页面展示使用 orderInfo.amount(真实价格),调接口仅用 PAY_AMOUNT 调起验证
 * TODO: 上线前将接口金额改回 orderInfo.amount
 */
const PAY_AMOUNT = 0.01

/** 从后端不同形态返回中提取支付跳转 URL */
const extractPayUrl = (res: RechargeAlipayH5OrderResult): string => {
  if (!res) return ''
  if (typeof res === 'string') return res
  return (
    res.payUrl ||
    res.payURL ||
    res.url ||
    res.body ||
    res.form ||
    ''
  )
}

const Payment = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  /** 后端返回的支付宝跳转 URL(点击支付后才拿到) */
  const [alipayUrl, setAlipayUrl] = useState<string>('')

  // 从路由状态获取订单信息(支持从登录页或注册页跳转)
  const stateData = location.state || {}

  // 订单信息
  const orderInfo = {
    memberId: stateData.memberId || '',
    memberType: stateData.memberType || '个人会员',
    amount: stateData.amount || 150.0,
    validPeriod: stateData.validPeriod || '5年',
    isRenew: stateData.isRenew || false, // 是否是续费
  }

  // 订单标题
  const orderSubject = orderInfo.isRenew
    ? '会员续费'
    : `${orderInfo.memberType}开通`

  // 点击支付宝支付按钮: 调后端创建订单,拿到支付链接后弹出引导弹窗
  const handlePayment = async () => {
    if (loading) return
    setLoading(true)
    try {
      const res = await createRechargeAlipayH5Order({
        amount: PAY_AMOUNT, // 测试阶段 0.01,上线前换回 orderInfo.amount
        subject: orderSubject,
      })
      const url = extractPayUrl(res)
      if (!url) {
        message.error('获取支付链接失败,请重试')
        return
      }
      setAlipayUrl(url)
      setModalVisible(true)
    } catch (e) {
      // request 拦截器已统一提示错误
      console.error('[createRechargeAlipayH5Order]', e)
    } finally {
      setLoading(false)
    }
  }

  // 在浏览器中打开支付页面
  const handleOpenInBrowser = () => {
    if (!alipayUrl) {
      message.warning('支付链接为空,请重新发起支付')
      return
    }
    setLoading(true)
    try {
      const newWindow = window.open(alipayUrl, '_blank')
      if (!newWindow) {
        message.warning('浏览器拦截了弹窗,请复制链接手动打开')
      } else {
        message.success('已在浏览器中打开支付页面,请完成支付')
      }
    } catch (error) {
      message.error('打开支付页面失败,请复制链接手动打开')
    } finally {
      setLoading(false)
    }
  }

  // TODO: 当后端提供支付结果查询接口后,在这里调用接口验证支付状态再跳转到会员权益页

  return (
    <div className="payment-page">
      <div className="payment-header">
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          className="back-btn"
        />
        <h1 className="payment-title">
          {orderInfo.isRenew ? '会员续费' : '订单支付'}
        </h1>
      </div>

      <div className="payment-container">
        {/* 订单信息 */}
        <Card title="订单信息" className="payment-card" bordered={false}>
          <div className="order-info">
            <div className="order-item">
              <span className="order-label">会员类型</span>
              <span className="order-value">{orderInfo.memberType}</span>
            </div>
            <div className="order-item">
              <span className="order-label">有效期限</span>
              <span className="order-value">{orderInfo.validPeriod}</span>
            </div>
            <div className="order-item amount-item">
              <span className="order-label">{orderInfo.isRenew ? '续费金额' : '应付金额'}</span>
              <span className="order-value amount-value">¥{orderInfo.amount.toFixed(2)}</span>
            </div>
          </div>
        </Card>

        {/* 支付方式 */}
        <Card title="支付方式" className="payment-card" bordered={false}>
          <div className="payment-method alipay-method">
            <div className="method-icon alipay-icon">
              <svg viewBox="0 0 1024 1024" width="40" height="40">
                <path d="M902.7 729.5c-12.8-4.3-238.7-79.4-344.6-130.7 39.9-69.5 71.7-148.5 92.4-232.6H471.6V298.7h222.5v-37.3H471.6V149.3h-90.8c-15.9 0-15.9 15.7-15.9 15.7v96.4H140.1v37.3h224.8v68.1H179.4V404h359.5c-13 46.5-30.6 90.7-51.5 130.6-116.6-38.6-241-69.9-319-50.7C118 496.3 86 519.6 67.2 549.5c-86.4 137.5 74.6 215.7 173.7 215.7 145.3 0 269.7-71.4 365.6-186.4C751.5 644.5 960 729.5 960 729.5V261.4c0 209.5-22.8 468.1-57.3 468.1zM229.6 707.6c-141.4 0-182.3-111.3-114.9-150.6 22.6-13.2 53.6-19.2 88.7-19.2 50.4 0 109.5 12.5 168.1 30.4-37.4 51.7-110.9 139.4-141.9 139.4z" fill="#1677FF"/>
              </svg>
            </div>
            <div className="method-info">
              <div className="method-name">支付宝支付</div>
              <div className="method-desc">推荐使用支付宝安全支付</div>
            </div>
            <div className="method-checked">
              <svg viewBox="0 0 1024 1024" width="24" height="24">
                <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m193.4 398.4L437.1 730.7c-12.5 12.5-32.8 12.5-45.3 0L228.5 567.3c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l140.6 140.6 245.3-245.3c12.5-12.5 32.8-12.5 45.3 0s12.5 32.8 0 45.3z" fill="#1677FF"/>
              </svg>
            </div>
          </div>
        </Card>

        {/* 支付按钮 */}
        <Button
          type="primary"
          className="pay-btn alipay-btn"
          onClick={handlePayment}
          loading={loading}
          block
          size="large"
        >
          支付宝支付 ¥{orderInfo.amount.toFixed(2)}
        </Button>

        <p className="payment-tips">
          支付即表示您同意会员服务协议
        </p>
      </div>

      {/* 引导用户在浏览器中打开支付页面的弹窗 */}
      <Modal
        title="前往支付宝完成支付"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        centered
        maskClosable={false}
        className="alipay-modal"
      >
        <div className="alipay-modal-content">
          <p className="alipay-modal-tip">
            点击下方按钮,将在浏览器中打开支付宝支付页面,完成支付后请返回本页面。
          </p>

          <Button
            type="primary"
            icon={<GlobalOutlined />}
            className="alipay-action-btn primary"
            onClick={handleOpenInBrowser}
            loading={loading}
            block
            size="large"
          >
            在浏览器中打开支付页面
          </Button>
        </div>
      </Modal>
    </div>
  )
}

export default Payment
