import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';
import '../../../../shared/widgets/genex_button.dart';

/// A3. 确认订单 + 支付页面
///
/// 券信息摘要、数量选择、价格计算、支付方式选择
/// 支付成功：成功动画、订单号、「查看我的券」「继续逛」
class OrderConfirmPage extends StatefulWidget {
  const OrderConfirmPage({super.key});

  @override
  State<OrderConfirmPage> createState() => _OrderConfirmPageState();
}

class _OrderConfirmPageState extends State<OrderConfirmPage> {
  int _quantity = 1;
  int _selectedPayment = 0;

  double get _unitPrice => 21.25;
  double get _totalPrice => _unitPrice * _quantity;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 20),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text('确认订单'),
      ),
      body: SingleChildScrollView(
        padding: AppSpacing.pagePadding,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 16),

            // Coupon Info Summary
            _buildCouponSummary(),
            const SizedBox(height: 16),

            // Quantity Selector
            _buildQuantitySelector(),
            const SizedBox(height: 16),

            // Payment Method
            _buildPaymentMethods(),
            const SizedBox(height: 16),

            // Price Breakdown
            _buildPriceBreakdown(),
            const SizedBox(height: 16),

            // Utility Track Notice
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: AppColors.successLight,
                borderRadius: AppSpacing.borderRadiusSm,
              ),
              child: Row(
                children: [
                  Icon(Icons.verified_user_rounded, size: 16,
                      color: AppColors.utilityTrack),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '您正在购买消费券用于消费',
                      style: AppTypography.bodySmall.copyWith(
                        color: AppColors.gray700,
                      ),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 100),
          ],
        ),
      ),

      // Bottom Pay Bar
      bottomNavigationBar: Container(
        padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
        decoration: const BoxDecoration(
          color: AppColors.surface,
          border: Border(top: BorderSide(color: AppColors.borderLight)),
        ),
        child: Row(
          children: [
            Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('合计', style: AppTypography.caption),
                Text(
                  '\$${_totalPrice.toStringAsFixed(2)}',
                  style: AppTypography.priceMedium,
                ),
              ],
            ),
            const SizedBox(width: 20),
            Expanded(
              child: GenexButton(
                label: '确认支付',
                onPressed: () => _showPaymentAuth(context),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCouponSummary() {
    return Container(
      padding: AppSpacing.cardPadding,
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Row(
        children: [
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: AppColors.primarySurface,
              borderRadius: AppSpacing.borderRadiusSm,
            ),
            child: Icon(Icons.confirmation_number_outlined,
                color: AppColors.primary.withValues(alpha: 0.4), size: 28),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Starbucks', style: AppTypography.caption),
                Text('星巴克 \$25 礼品卡', style: AppTypography.labelMedium),
                const SizedBox(height: 4),
                Row(
                  children: [
                    Text(
                      '\$21.25',
                      style: AppTypography.priceSmall.copyWith(fontSize: 15),
                    ),
                    const SizedBox(width: 6),
                    Text('\$25', style: AppTypography.priceOriginal),
                    const SizedBox(width: 6),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
                      decoration: BoxDecoration(
                        gradient: AppColors.primaryGradient,
                        borderRadius: AppSpacing.borderRadiusFull,
                      ),
                      child: Text('8.5折', style: AppTypography.discountBadge),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQuantitySelector() {
    return Container(
      padding: AppSpacing.cardPadding,
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text('购买数量', style: AppTypography.labelMedium),
          Row(
            children: [
              _buildQtyButton(Icons.remove_rounded, () {
                if (_quantity > 1) setState(() => _quantity--);
              }),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Text('$_quantity', style: AppTypography.h3),
              ),
              _buildQtyButton(Icons.add_rounded, () {
                if (_quantity < 10) setState(() => _quantity++);
              }),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildQtyButton(IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 32,
        height: 32,
        decoration: BoxDecoration(
          color: AppColors.gray50,
          borderRadius: AppSpacing.borderRadiusSm,
          border: Border.all(color: AppColors.border),
        ),
        child: Icon(icon, size: 18, color: AppColors.textPrimary),
      ),
    );
  }

  Widget _buildPaymentMethods() {
    final methods = [
      ('银行卡/信用卡', Icons.credit_card_rounded),
      ('Apple Pay', Icons.apple_rounded),
    ];

    return Container(
      padding: AppSpacing.cardPadding,
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('支付方式', style: AppTypography.labelMedium),
          const SizedBox(height: 12),
          ...methods.asMap().entries.map((entry) {
            final isSelected = _selectedPayment == entry.key;
            return GestureDetector(
              onTap: () => setState(() => _selectedPayment = entry.key),
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  border: entry.key < methods.length - 1
                      ? const Border(bottom: BorderSide(color: AppColors.borderLight))
                      : null,
                ),
                child: Row(
                  children: [
                    Icon(entry.value.$2, size: 24, color: AppColors.textPrimary),
                    const SizedBox(width: 12),
                    Text(entry.value.$1, style: AppTypography.bodyMedium),
                    const Spacer(),
                    Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: isSelected ? AppColors.primary : AppColors.border,
                          width: isSelected ? 6 : 1.5,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _buildPriceBreakdown() {
    return Container(
      padding: AppSpacing.cardPadding,
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        children: [
          _priceRow('单价', '\$${_unitPrice.toStringAsFixed(2)}'),
          const SizedBox(height: 8),
          _priceRow('数量', '×$_quantity'),
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 10),
            child: Divider(),
          ),
          _priceRow(
            '合计',
            '\$${_totalPrice.toStringAsFixed(2)}',
            valueStyle: AppTypography.priceMedium,
          ),
          const SizedBox(height: 4),
          Align(
            alignment: Alignment.centerRight,
            child: Text(
              '比面值节省 \$${(25.0 * _quantity - _totalPrice).toStringAsFixed(2)}',
              style: AppTypography.caption.copyWith(color: AppColors.success),
            ),
          ),
        ],
      ),
    );
  }

  Widget _priceRow(String label, String value, {TextStyle? valueStyle}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label, style: AppTypography.bodyMedium.copyWith(color: AppColors.textSecondary)),
        Text(value, style: valueStyle ?? AppTypography.labelMedium),
      ],
    );
  }

  void _showPaymentAuth(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (ctx) => Container(
        padding: const EdgeInsets.fromLTRB(20, 0, 20, 40),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(height: 8),
            Container(
              width: 36, height: 4,
              decoration: BoxDecoration(
                color: AppColors.gray300,
                borderRadius: AppSpacing.borderRadiusFull,
              ),
            ),
            const SizedBox(height: 20),
            Text('确认支付', style: AppTypography.h2),
            const SizedBox(height: 8),
            Text(
              '\$${_totalPrice.toStringAsFixed(2)}',
              style: AppTypography.priceLarge.copyWith(fontSize: 36),
            ),
            const SizedBox(height: 4),
            Text('星巴克 \$25 礼品卡 × $_quantity',
                style: AppTypography.bodySmall),
            const SizedBox(height: 32),
            // Biometric / Password
            Container(
              width: 64, height: 64,
              decoration: BoxDecoration(
                color: AppColors.primarySurface,
                shape: BoxShape.circle,
              ),
              child: const Icon(Icons.fingerprint_rounded,
                  size: 36, color: AppColors.primary),
            ),
            const SizedBox(height: 12),
            Text('请验证指纹或面容以完成支付', style: AppTypography.bodySmall),
            const SizedBox(height: 24),
            GenexButton(
              label: '使用密码支付',
              variant: GenexButtonVariant.text,
              onPressed: () {
                Navigator.pop(ctx);
                Navigator.pushNamed(context, '/payment');
              },
            ),
          ],
        ),
      ),
    );
  }
}
