import React, { useState, useEffect } from 'react';
import { t } from '@/i18n';
import Taro from '@tarojs/taro';
import { getCouponDetail, purchaseCoupon } from '../../services/coupon';
import type { CouponItem } from '../../services/coupon';
// Taro mini-program component (WeChat / Alipay)

/**
 * E1. 小程序核心页面 - 购买/确认订单页
 *
 * Coupon summary card, quantity selector, payment method,
 * price breakdown, fixed bottom bar with confirm button
 */

const PurchasePage: React.FC = () => {
  const [coupon, setCoupon] = useState<CouponItem | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [quantity, setQuantity] = useState(1);

  useEffect(() => {
    const params = Taro.getCurrentInstance().router?.params;
    const id = params?.id;
    if (!id) {
      setLoading(false);
      return;
    }
    getCouponDetail(id)
      .then((data) => setCoupon(data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <view className="purchase-page" style={{ display: 'flex', justifyContent: 'center', paddingTop: '200rpx' }}>
        <text style={{ color: '#A0A8BE', fontSize: '28rpx' }}>{t('loading') || '加载中...'}</text>
      </view>
    );
  }

  if (!coupon) {
    return (
      <view className="purchase-page" style={{ display: 'flex', justifyContent: 'center', paddingTop: '200rpx' }}>
        <text style={{ color: '#A0A8BE', fontSize: '28rpx' }}>{t('empty') || '未找到券信息'}</text>
      </view>
    );
  }

  const unitPrice = coupon.currentPrice;
  const faceValue = coupon.faceValue;
  const discount = ((unitPrice / faceValue) * 10).toFixed(1) + '折';
  const totalPrice = (unitPrice * quantity).toFixed(2);
  const totalFace = (faceValue * quantity).toFixed(2);
  const savings = ((faceValue - unitPrice) * quantity).toFixed(2);

  const handleMinus = () => {
    if (quantity > 1) setQuantity(quantity - 1);
  };

  const handlePlus = () => {
    if (quantity < 10) setQuantity(quantity + 1);
  };

  const handleConfirm = () => {
    if (submitting) return;
    setSubmitting(true);
    purchaseCoupon(coupon.id, quantity)
      .then((result) => {
        Taro.navigateTo({
          url: `/pages/payment-success/index?orderId=${result.orderId}&couponName=${encodeURIComponent(coupon.name)}&amount=${totalPrice}`,
        });
      })
      .catch(() => {})
      .finally(() => setSubmitting(false));
  };

  return (
    <view className="purchase-page">
      {/* Coupon Summary Card */}
      <view className="coupon-summary">
        <view className="summary-image">
          <text className="summary-icon">🎫</text>
        </view>
        <view className="summary-info">
          <text className="summary-brand">{coupon.brandName || coupon.category}</text>
          <text className="summary-name">{coupon.name}</text>
          <view className="summary-price-row">
            <text className="summary-price">¥{unitPrice.toFixed(2)}</text>
            <text className="summary-face">¥{faceValue}</text>
            <view className="summary-discount">
              <text className="summary-discount-text">{discount}</text>
            </view>
          </view>
        </view>
      </view>

      {/* Quantity Selector */}
      <view className="section-card">
        <view className="section-row">
          <text className="section-label">{t('purchase_quantity')}</text>
          <view className="qty-selector">
            <view className={`qty-btn ${quantity <= 1 ? 'qty-btn-disabled' : ''}`} onClick={handleMinus}>
              <text className="qty-btn-text">-</text>
            </view>
            <view className="qty-value">
              <text className="qty-value-text">{quantity}</text>
            </view>
            <view className={`qty-btn ${quantity >= 10 ? 'qty-btn-disabled' : ''}`} onClick={handlePlus}>
              <text className="qty-btn-text">+</text>
            </view>
          </view>
        </view>
      </view>

      {/* Payment Method */}
      <view className="section-card">
        <text className="card-title">{t('purchase_payment_method')}</text>
        <view className="payment-row">
          <view className="payment-icon-wrap">
            <text className="payment-icon">💬</text>
          </view>
          <text className="payment-name">{t('purchase_wechat_pay')}</text>
          <view className="payment-check">
            <text className="payment-check-text">✓</text>
          </view>
        </view>
      </view>

      {/* Price Breakdown */}
      <view className="section-card">
        <text className="card-title">{t('purchase_price_detail')}</text>
        <view className="price-row">
          <text className="price-label">{t('purchase_unit_price')}</text>
          <text className="price-value">¥{unitPrice.toFixed(2)}</text>
        </view>
        <view className="price-row">
          <text className="price-label">{t('purchase_count')}</text>
          <text className="price-value">x{quantity}</text>
        </view>
        <view className="price-divider" />
        <view className="price-row price-row-total">
          <text className="price-label-total">{t('order_total')}</text>
          <text className="price-value-total">¥{totalPrice}</text>
        </view>
        <view className="savings-badge">
          <text className="savings-icon">🏷️</text>
          <text className="savings-text">{t('purchase_save_badge')} ¥{savings}</text>
        </view>
      </view>

      {/* Info Notice */}
      <view className="info-notice">
        <text className="notice-icon">🛡️</text>
        <text className="notice-text">{t('purchase_buying_note')}</text>
      </view>

      {/* Fixed Bottom Bar */}
      <view className="bottom-bar">
        <view className="bottom-left">
          <text className="bottom-label">{t('order_total')}</text>
          <text className="bottom-price">¥{totalPrice}</text>
        </view>
        <view className="bottom-btn" onClick={handleConfirm}>
          <text className="bottom-btn-text">{submitting ? (t('loading') || '处理中...') : t('purchase_confirm_pay')}</text>
        </view>
      </view>
    </view>
  );
};

export default PurchasePage;

/*
CSS (index.scss):

.purchase-page { padding: 24rpx 32rpx; padding-bottom: 180rpx; background: #F8F9FC; min-height: 100vh; }

.coupon-summary {
  display: flex; padding: 24rpx;
  background: white; border-radius: 16rpx;
  border: 1rpx solid #F1F3F8; margin-bottom: 20rpx;
}
.summary-image {
  width: 140rpx; height: 140rpx; background: #F3F1FF;
  border-radius: 12rpx; display: flex;
  align-items: center; justify-content: center; flex-shrink: 0;
}
.summary-icon { font-size: 48rpx; }
.summary-info {
  flex: 1; padding-left: 20rpx;
  display: flex; flex-direction: column; justify-content: space-between;
}
.summary-brand { font-size: 22rpx; color: #A0A8BE; }
.summary-name { font-size: 28rpx; font-weight: 500; color: #141723; margin-top: 4rpx; }
.summary-price-row { display: flex; align-items: flex-end; margin-top: 8rpx; }
.summary-price { font-size: 32rpx; font-weight: 700; color: #6C5CE7; }
.summary-face { font-size: 22rpx; color: #A0A8BE; text-decoration: line-through; margin-left: 8rpx; }
.summary-discount {
  margin-left: 8rpx; padding: 2rpx 10rpx;
  background: linear-gradient(135deg, #6C5CE7, #9B8FFF);
  border-radius: 999rpx;
}
.summary-discount-text { color: white; font-size: 20rpx; font-weight: 700; }

.section-card {
  background: white; border-radius: 16rpx; padding: 24rpx;
  border: 1rpx solid #F1F3F8; margin-bottom: 20rpx;
}
.card-title { font-size: 28rpx; font-weight: 600; color: #141723; margin-bottom: 20rpx; }

.section-row {
  display: flex; justify-content: space-between; align-items: center;
}
.section-label { font-size: 28rpx; font-weight: 500; color: #141723; }

.qty-selector { display: flex; align-items: center; }
.qty-btn {
  width: 56rpx; height: 56rpx; border-radius: 12rpx;
  background: #F3F1FF; display: flex;
  align-items: center; justify-content: center;
}
.qty-btn-disabled { background: #F1F3F8; opacity: 0.5; }
.qty-btn-text { font-size: 32rpx; font-weight: 600; color: #6C5CE7; }
.qty-value {
  width: 80rpx; display: flex; align-items: center; justify-content: center;
}
.qty-value-text { font-size: 32rpx; font-weight: 600; color: #141723; }

.payment-row {
  display: flex; align-items: center; padding: 12rpx 0;
}
.payment-icon-wrap {
  width: 48rpx; height: 48rpx; border-radius: 12rpx;
  background: #E6FAF3; display: flex;
  align-items: center; justify-content: center; margin-right: 16rpx;
}
.payment-icon { font-size: 28rpx; }
.payment-name { flex: 1; font-size: 28rpx; color: #141723; }
.payment-check {
  width: 40rpx; height: 40rpx; border-radius: 50%;
  background: #00C48C; display: flex;
  align-items: center; justify-content: center;
}
.payment-check-text { color: white; font-size: 24rpx; font-weight: 700; }

.price-row {
  display: flex; justify-content: space-between; padding: 12rpx 0;
}
.price-label { font-size: 26rpx; color: #5C6478; }
.price-value { font-size: 26rpx; color: #141723; }
.price-divider { height: 1rpx; background: #F1F3F8; margin: 12rpx 0; }
.price-row-total { padding-top: 16rpx; }
.price-label-total { font-size: 28rpx; font-weight: 600; color: #141723; }
.price-value-total { font-size: 36rpx; font-weight: 700; color: #6C5CE7; }

.savings-badge {
  display: flex; align-items: center; margin-top: 12rpx;
  padding: 10rpx 16rpx; background: #E6FAF3; border-radius: 8rpx;
}
.savings-icon { font-size: 24rpx; margin-right: 8rpx; }
.savings-text { font-size: 24rpx; color: #00C48C; font-weight: 500; }

.info-notice {
  display: flex; align-items: center;
  padding: 20rpx 24rpx; background: #E6FAF3;
  border-radius: 12rpx; margin-bottom: 20rpx;
}
.notice-icon { font-size: 28rpx; margin-right: 12rpx; }
.notice-text { font-size: 24rpx; color: #3D4459; }

.bottom-bar {
  position: fixed; bottom: 0; left: 0; right: 0;
  display: flex; align-items: center; justify-content: space-between;
  padding: 20rpx 32rpx; padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: white; border-top: 1rpx solid #F1F3F8;
}
.bottom-left { display: flex; flex-direction: column; }
.bottom-label { font-size: 22rpx; color: #A0A8BE; }
.bottom-price { font-size: 40rpx; font-weight: 700; color: #6C5CE7; }
.bottom-btn {
  padding: 20rpx 56rpx; border-radius: 16rpx;
  background: linear-gradient(135deg, #6C5CE7, #9B8FFF);
}
.bottom-btn-text { color: white; font-size: 30rpx; font-weight: 600; }
*/
