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

/// A10. 挂单出售页面
///
/// 消费者将持有的券挂到二级市场出售
/// 自定义定价 + AI推荐价格 + 手续费预览
class SellOrderPage extends StatefulWidget {
  const SellOrderPage({super.key});

  @override
  State<SellOrderPage> createState() => _SellOrderPageState();
}

class _SellOrderPageState extends State<SellOrderPage> {
  final _priceController = TextEditingController(text: '22.50');
  double _faceValue = 25.0;

  double get _price => double.tryParse(_priceController.text) ?? 0;
  double get _discount => _faceValue > 0 ? _price / _faceValue * 100 : 0;
  double get _fee => _price * 0.015; // 1.5% 手续费
  double get _receive => _price - _fee;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('挂单出售')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Coupon Info
            Container(
              padding: AppSpacing.cardPadding,
              decoration: BoxDecoration(
                color: AppColors.surface,
                borderRadius: AppSpacing.borderRadiusMd,
                border: Border.all(color: AppColors.borderLight),
              ),
              child: Row(
                children: [
                  Container(
                    width: 56,
                    height: 56,
                    decoration: BoxDecoration(
                      color: AppColors.primarySurface,
                      borderRadius: AppSpacing.borderRadiusMd,
                    ),
                    child: const Icon(Icons.confirmation_number_rounded, color: AppColors.primary, size: 28),
                  ),
                  const SizedBox(width: 14),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('星巴克 \$25 礼品卡', style: AppTypography.labelLarge),
                        const SizedBox(height: 4),
                        Text('面值 \$$_faceValue · 信用 AAA', style: AppTypography.bodySmall),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 24),

            // Price Input
            Text('设定售价', style: AppTypography.h3),
            const SizedBox(height: 12),
            TextField(
              controller: _priceController,
              keyboardType: const TextInputType.numberWithOptions(decimal: true),
              decoration: const InputDecoration(
                prefixText: '\$ ',
                labelText: '售价',
                suffixText: 'USD',
              ),
              style: AppTypography.priceLarge,
              onChanged: (_) => setState(() {}),
            ),
            const SizedBox(height: 8),

            // AI Suggestion
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: AppColors.primarySurface,
                borderRadius: AppSpacing.borderRadiusSm,
              ),
              child: Row(
                children: [
                  const Icon(Icons.auto_awesome_rounded, color: AppColors.primary, size: 16),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'AI建议售价：\$22.50（9折），此价格成交概率最高',
                      style: AppTypography.caption.copyWith(color: AppColors.primary),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 24),

            // Fee Breakdown
            Container(
              padding: AppSpacing.cardPadding,
              decoration: BoxDecoration(
                color: AppColors.surface,
                borderRadius: AppSpacing.borderRadiusMd,
                border: Border.all(color: AppColors.borderLight),
              ),
              child: Column(
                children: [
                  _buildRow('售价', '\$${_price.toStringAsFixed(2)}'),
                  _buildRow('折扣率', '${_discount.toStringAsFixed(1)}%'),
                  _buildRow('平台手续费 (1.5%)', '-\$${_fee.toStringAsFixed(2)}'),
                  const Divider(height: 24),
                  _buildRow('预计到账', '\$${_receive.toStringAsFixed(2)}', isBold: true),
                ],
              ),
            ),
            const SizedBox(height: 16),

            // Market Info
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: AppColors.infoLight,
                borderRadius: AppSpacing.borderRadiusSm,
              ),
              child: Row(
                children: [
                  const Icon(Icons.info_outline_rounded, color: AppColors.info, size: 16),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '当前市场均价 \$22.80 · 最近24小时成交 42 笔',
                      style: AppTypography.caption.copyWith(color: AppColors.info),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: Container(
        padding: const EdgeInsets.all(20),
        child: SizedBox(
          height: AppSpacing.buttonHeight,
          child: ElevatedButton(
            onPressed: () => _confirmSell(context),
            child: const Text('确认挂单'),
          ),
        ),
      ),
    );
  }

  Widget _buildRow(String label, String value, {bool isBold = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: AppTypography.bodyMedium.copyWith(color: AppColors.textSecondary)),
          Text(value, style: isBold ? AppTypography.priceSmall : AppTypography.labelMedium),
        ],
      ),
    );
  }

  void _confirmSell(BuildContext context) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('挂单成功'),
        content: const Text('您的券已挂到市场，当有买家下单时将自动成交。'),
        actions: [
          TextButton(onPressed: () { Navigator.pop(ctx); Navigator.pop(context); }, child: const Text('确定')),
        ],
      ),
    );
  }
}
