import React, { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { t } from '@/i18n';
import { getCouponDetail, getNearbyStores, getSimilarCoupons } from '../../services/coupon';
import type { CouponItem } from '../../services/coupon';
// Taro mini-program - Coupon Detail + Purchase

/**
 * E1. 小程序核心页面 - 券详情 + 购买
 *
 * 同App，微信支付/支付宝支付
 */

const DetailPage: React.FC = () => {
  const [coupon, setCoupon] = useState<CouponItem | null>(null);
  const [stores, setStores] = useState<Array<{ id: string; name: string; address: string; distance?: number }>>([]);
  const [similarCoupons, setSimilarCoupons] = useState<CouponItem[]>([]);
  const [loading, setLoading] = useState(true);

  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));

    getNearbyStores(id)
      .then((data) => setStores(data))
      .catch(() => {});

    getSimilarCoupons(id)
      .then((data) => setSimilarCoupons(data))
      .catch(() => {});
  }, []);

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

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

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

  return (
    <view className="detail-page">
      {/* Coupon Image */}
      <view className="detail-hero">
        <view className="detail-hero-bg">
          <text className="hero-icon">🎫</text>
        </view>
      </view>

      {/* Main Info */}
      <view className="detail-info">
        <view className="brand-row">
          <view className="brand-logo">{(coupon.brandName || coupon.name)[0]}</view>
          <view className="brand-info">
            <text className="brand-name">{coupon.brandName || coupon.category}</text>
            {coupon.creditRating && (
              <view className="credit-badge">
                <text className="credit-text">{coupon.creditRating}</text>
              </view>
            )}
          </view>
        </view>
        <text className="coupon-title">{coupon.name}</text>

        {/* Price */}
        <view className="price-card">
          <view className="price-row">
            <text className="price-symbol">¥</text>
            <text className="price-value">{coupon.currentPrice.toFixed(2)}</text>
            <text className="price-original">¥{coupon.faceValue}</text>
            <view className="discount-tag">{discount}</view>
          </view>
          <text className="price-save">{t('coupon_price_save')} ¥{savings}</text>
        </view>

        {/* Info List */}
        <view className="info-card">
          {[
            { label: t('coupon_face_value'), value: `¥${coupon.faceValue.toFixed(2)}` },
            { label: t('coupon_valid_until'), value: coupon.expiryDate ? coupon.expiryDate.split('T')[0].replace(/-/g, '/') : '--' },
            { label: t('coupon_type_label'), value: coupon.couponType === 'consumer' ? t('coupon_type_consumer') : coupon.couponType },
            { label: t('coupon_store'), value: stores.length > 0 ? `${stores.length} ${t('coupon_stores_count')}` : t('coupon_stores_count') },
          ].map((item, i) => (
            <view key={i} className="info-row">
              <text className="info-label">{item.label}</text>
              <text className="info-value">{item.value}</text>
            </view>
          ))}
        </view>

        {/* Rules */}
        <view className="rules-card">
          <text className="rules-title">{t('coupon_description')}</text>
          {coupon.description ? (
            <view className="rule-item">
              <text className="rule-text">{coupon.description}</text>
            </view>
          ) : (
            [
              t('coupon_rule_universal'),
              t('coupon_rule_giftable'),
              t('coupon_rule_anytime'),
              t('coupon_rule_no_stack'),
            ].map((rule, i) => (
              <view key={i} className="rule-item">
                <text className="rule-dot">•</text>
                <text className="rule-text">{rule}</text>
              </view>
            ))
          )}
        </view>

        {/* Utility Track Notice */}
        <view className="utility-notice">
          <text className="utility-icon">✓</text>
          <text className="utility-text">{t('coupon_utility_notice')}</text>
        </view>
      </view>

      {/* Nearby Stores */}
      {stores.length > 0 && (
        <view className="section-card">
          <view className="section-header">
            <text className="section-title">{t('detail_nearby_stores')}</text>
            <text className="section-link">{t('detail_view_all')} &gt;</text>
          </view>
          {stores.slice(0, 3).map((store) => (
            <view key={store.id} className="store-row">
              <text className="store-name">{store.name}</text>
              <view className="store-distance-badge">
                <text className="store-distance">{store.distance ? `${store.distance}km` : store.address}</text>
              </view>
            </view>
          ))}
        </view>
      )}

      {/* Similar Coupons */}
      {similarCoupons.length > 0 && (
        <view className="section-card">
          <view className="section-header">
            <text className="section-title">{t('detail_similar_coupons')}</text>
            <text className="section-link">{t('more')} &gt;</text>
          </view>
          <scroll-view scrollX className="similar-scroll">
            {similarCoupons.map((item) => (
              <view
                key={item.id}
                className="similar-card"
                onClick={() => Taro.navigateTo({ url: `/pages/detail/index?id=${item.id}` })}
              >
                <view className="similar-icon-wrap">
                  <text className="similar-icon">🎫</text>
                </view>
                <text className="similar-name">{item.name}</text>
                <view className="similar-price-row">
                  <text className="similar-price">¥{item.currentPrice.toFixed(2)}</text>
                  <text className="similar-discount">
                    {((item.currentPrice / item.faceValue) * 10).toFixed(1)}折
                  </text>
                </view>
              </view>
            ))}
          </scroll-view>
        </view>
      )}

      {/* Bottom Buy Bar */}
      <view className="buy-bar">
        <view className="buy-bar-price">
          <text className="buy-label">{t('order_total')}</text>
          <text className="buy-price">¥{coupon.currentPrice.toFixed(2)}</text>
        </view>
        <view className="buy-button" onClick={() => Taro.navigateTo({ url: `/pages/purchase/index?id=${coupon.id}` })}>
          <text className="buy-button-text">{t('coupon_buy_now')}</text>
        </view>
      </view>
    </view>
  );
};

export default DetailPage;

/*
CSS (index.scss):

.detail-page { padding-bottom: 140rpx; background: #F8F9FC; }

.detail-hero { height: 400rpx; }
.detail-hero-bg {
  height: 100%; background: linear-gradient(135deg, #6C5CE7, #9B8FFF);
  display: flex; align-items: center; justify-content: center;
}
.hero-icon { font-size: 120rpx; opacity: 0.3; }

.detail-info { margin-top: -40rpx; position: relative; z-index: 1; padding: 0 32rpx; }

.brand-row {
  display: flex; align-items: center;
  background: white; border-radius: 24rpx; padding: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.06);
}
.brand-logo {
  width: 64rpx; height: 64rpx; border-radius: 12rpx;
  background: #F1F3F8; display: flex; align-items: center; justify-content: center;
  font-size: 28rpx; font-weight: 700; color: #6C5CE7;
}
.brand-info { margin-left: 16rpx; display: flex; align-items: center; gap: 12rpx; }
.brand-name { font-size: 28rpx; color: #5C6478; }
.credit-badge {
  padding: 2rpx 12rpx; background: rgba(0,196,140,0.1);
  border: 1rpx solid rgba(0,196,140,0.3); border-radius: 999rpx;
}
.credit-text { font-size: 20rpx; color: #00C48C; font-weight: 700; }

.coupon-title {
  display: block; font-size: 36rpx; font-weight: 600; color: #141723;
  margin-top: 20rpx; margin-bottom: 16rpx;
}

.price-card {
  background: #F3F1FF; border-radius: 16rpx; padding: 24rpx; margin-bottom: 16rpx;
}
.price-row { display: flex; align-items: flex-end; }
.price-symbol { font-size: 28rpx; font-weight: 700; color: #6C5CE7; }
.price-value { font-size: 52rpx; font-weight: 700; color: #6C5CE7; line-height: 1; }
.price-original { font-size: 24rpx; color: #A0A8BE; text-decoration: line-through; margin-left: 12rpx; }
.discount-tag {
  margin-left: 12rpx; padding: 4rpx 12rpx;
  background: linear-gradient(135deg, #6C5CE7, #9B8FFF);
  color: white; font-size: 20rpx; font-weight: 700; border-radius: 999rpx;
}
.price-save { font-size: 22rpx; color: #00C48C; margin-top: 8rpx; }

.info-card {
  background: white; border-radius: 16rpx; padding: 24rpx; margin-bottom: 16rpx;
  border: 1rpx solid #F1F3F8;
}
.info-row {
  display: flex; justify-content: space-between; padding: 14rpx 0;
  border-bottom: 1rpx solid #F1F3F8;
}
.info-row:last-child { border-bottom: none; }
.info-label { font-size: 26rpx; color: #5C6478; }
.info-value { font-size: 26rpx; color: #141723; font-weight: 500; }

.rules-card {
  background: white; border-radius: 16rpx; padding: 24rpx; margin-bottom: 16rpx;
  border: 1rpx solid #F1F3F8;
}
.rules-title { font-size: 28rpx; font-weight: 500; margin-bottom: 16rpx; }
.rule-item { display: flex; align-items: center; margin-bottom: 12rpx; }
.rule-dot { color: #A0A8BE; margin-right: 12rpx; }
.rule-text { font-size: 24rpx; color: #5C6478; }

.utility-notice {
  display: flex; align-items: center; padding: 16rpx 24rpx;
  background: #E6FAF3; border-radius: 12rpx;
}
.utility-icon { color: #00C48C; margin-right: 12rpx; font-weight: 700; }
.utility-text { font-size: 24rpx; color: #3D4459; }

.section-card {
  background: white; border-radius: 16rpx; padding: 24rpx;
  margin: 0 32rpx 16rpx; border: 1rpx solid #F1F3F8;
}
.section-header {
  display: flex; justify-content: space-between; align-items: center;
  margin-bottom: 16rpx;
}
.section-title { font-size: 28rpx; font-weight: 600; color: #141723; }
.section-link { font-size: 24rpx; color: #6C5CE7; }

.store-row {
  display: flex; justify-content: space-between; align-items: center;
  padding: 16rpx 0; border-bottom: 1rpx solid #F1F3F8;
}
.store-row:last-child { border-bottom: none; }
.store-name { font-size: 26rpx; color: #141723; }
.store-distance-badge {
  padding: 4rpx 16rpx; background: #F3F1FF; border-radius: 999rpx;
}
.store-distance { font-size: 22rpx; color: #6C5CE7; font-weight: 500; }

.similar-scroll { white-space: nowrap; }
.similar-card {
  display: inline-block; width: 200rpx; margin-right: 16rpx;
  background: #F8F9FC; border-radius: 12rpx; padding: 16rpx;
  vertical-align: top;
}
.similar-icon-wrap {
  width: 100%; height: 100rpx; background: #F3F1FF; border-radius: 8rpx;
  display: flex; align-items: center; justify-content: center;
  margin-bottom: 12rpx;
}
.similar-icon { font-size: 36rpx; }
.similar-name {
  font-size: 22rpx; color: #141723; font-weight: 500;
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  display: block; margin-bottom: 8rpx;
}
.similar-price-row { display: flex; align-items: center; }
.similar-price { font-size: 24rpx; color: #6C5CE7; font-weight: 700; }
.similar-discount {
  font-size: 18rpx; color: #9B8FFF; margin-left: 8rpx;
  padding: 2rpx 8rpx; background: #F3F1FF; border-radius: 999rpx;
}

.buy-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;
}
.buy-bar-price { display: flex; flex-direction: column; }
.buy-label { font-size: 22rpx; color: #A0A8BE; }
.buy-price { font-size: 40rpx; font-weight: 700; color: #6C5CE7; }
.buy-button {
  padding: 20rpx 48rpx; background: #6C5CE7; border-radius: 16rpx;
}
.buy-button-text { color: white; font-size: 30rpx; font-weight: 600; }
*/
