import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/router/routes.dart';
import '../../../core/utils/format_utils.dart';
import '../../../core/constants/app_colors.dart';
import '../../../data/models/c2c_order_model.dart';
import '../../providers/c2c_providers.dart';
import '../../providers/user_providers.dart';
import '../../providers/asset_providers.dart';
import '../../../data/models/capability_model.dart';

class C2cMarketPage extends ConsumerStatefulWidget {
  const C2cMarketPage({super.key});

  @override
  ConsumerState<C2cMarketPage> createState() => _C2cMarketPageState();
}

class _C2cMarketPageState extends ConsumerState<C2cMarketPage>
    with SingleTickerProviderStateMixin {
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _green = Color(0xFF10B981);
  static const Color _red = Color(0xFFEF4444);
  static const Color _darkText = Color(0xFF1F2937);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _bgGray = Color(0xFFF3F4F6);

  late TabController _tabController;
  int _currentTab = 0; // 0: 购买, 1: 出售, 2: 我的

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      setState(() {
        _currentTab = _tabController.index;
      });
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final user = ref.watch(userNotifierProvider);
    final accountSequence = user.accountSequence ?? '';
    final assetAsync = ref.watch(accountAssetProvider(accountSequence));
    final asset = assetAsync.valueOrNull;

    return Scaffold(
      backgroundColor: AppColors.backgroundOf(context),
      appBar: AppBar(
        backgroundColor: AppColors.cardOf(context),
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: AppColors.textPrimaryOf(context)),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'C2C交易',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: AppColors.textPrimaryOf(context),
          ),
        ),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.add_circle_outline, color: _orange),
            onPressed: () {
              final caps = ref.read(capabilitiesProvider).valueOrNull ?? CapabilityMap.defaultAll();
              if (!caps.c2cEnabled) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('您的C2C交易功能已被限制'), backgroundColor: _red),
                );
                return;
              }
              context.push(Routes.c2cPublish);
            },
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          labelColor: _orange,
          unselectedLabelColor: AppColors.textSecondaryOf(context),
          indicatorColor: _orange,
          indicatorWeight: 3,
          tabs: const [
            Tab(text: '购买'),
            Tab(text: '出售'),
            Tab(text: '我的'),
          ],
        ),
      ),
      body: Column(
        children: [
          // 资产概览
          _buildAssetOverview(context, asset),
          // 订单列表
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildOrderList(context, 'SELL'), // 购买页面显示卖单
                _buildOrderList(context, 'BUY'),  // 出售页面显示买单
                _buildMyOrderList(context, accountSequence),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAssetOverview(BuildContext context, asset) {
    final availableShares = asset?.availableShares ?? '0';
    final availableCash = asset?.availableCash ?? '0';

    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.cardOf(context),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '可用积分值',
                  style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context)),
                ),
                const SizedBox(height: 4),
                Text(
                  formatAmount(availableCash),
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: _orange,
                  ),
                ),
              ],
            ),
          ),
          Container(width: 1, height: 40, color: AppColors.borderOf(context)),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '可用积分值',
                    style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context)),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    formatAmount(availableCash),
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: _green,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildOrderList(BuildContext context, String type) {
    final ordersAsync = ref.watch(c2cOrdersProvider(type));

    return ordersAsync.when(
      loading: () => const Center(
        child: CircularProgressIndicator(color: _orange),
      ),
      error: (error, stack) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 48, color: AppColors.textMutedOf(context)),
            const SizedBox(height: 8),
            Text('加载失败', style: TextStyle(color: AppColors.textSecondaryOf(context))),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: () => ref.invalidate(c2cOrdersProvider(type)),
              child: const Text('重试'),
            ),
          ],
        ),
      ),
      data: (ordersPage) {
        final orders = ordersPage.data;
        if (orders.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.inbox_outlined, size: 64, color: AppColors.textMutedOf(context)),
                const SizedBox(height: 16),
                Text(
                  type == 'SELL' ? '暂无出售广告' : '暂无购买广告',
                  style: TextStyle(fontSize: 16, color: AppColors.textSecondaryOf(context)),
                ),
                const SizedBox(height: 8),
                Text(
                  '点击右上角发布广告',
                  style: TextStyle(fontSize: 14, color: AppColors.textMutedOf(context)),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: () async {
            ref.invalidate(c2cOrdersProvider(type));
          },
          child: ListView.builder(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            itemCount: orders.length,
            itemBuilder: (context, index) {
              final order = orders[index];
              return _buildOrderCard(context, order, type == 'SELL');
            },
          ),
        );
      },
    );
  }

  Widget _buildMyOrderList(BuildContext context, String accountSequence) {
    final ordersAsync = ref.watch(myC2cOrdersProvider);

    return ordersAsync.when(
      loading: () => const Center(
        child: CircularProgressIndicator(color: _orange),
      ),
      error: (error, stack) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 48, color: AppColors.textMutedOf(context)),
            const SizedBox(height: 8),
            Text('加载失败', style: TextStyle(color: AppColors.textSecondaryOf(context))),
          ],
        ),
      ),
      data: (ordersPage) {
        final orders = ordersPage.data;
        if (orders.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.history, size: 64, color: AppColors.textMutedOf(context)),
                const SizedBox(height: 16),
                Text(
                  '暂无订单记录',
                  style: TextStyle(fontSize: 16, color: AppColors.textSecondaryOf(context)),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: () async {
            ref.invalidate(myC2cOrdersProvider);
          },
          child: ListView.builder(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            itemCount: orders.length,
            itemBuilder: (context, index) {
              final order = orders[index];
              return _buildMyOrderCard(context, order, accountSequence);
            },
          ),
        );
      },
    );
  }

  Widget _buildOrderCard(BuildContext context, C2cOrderModel order, bool isBuyAction) {
    final user = ref.read(userNotifierProvider);
    final isMyOrder = order.makerAccountSequence == user.accountSequence;
    final isDark = AppColors.isDark(context);

    return GestureDetector(
      onTap: isMyOrder ? null : () => _showTakeOrderDialog(order, isBuyAction),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppColors.cardOf(context),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息和类型
            Row(
              children: [
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: (isBuyAction ? _green : _red).withOpacity(isDark ? 0.2 : 0.1),
                  ),
                  child: Center(
                    child: Text(
                      ((order.makerNickname?.isNotEmpty == true ? order.makerNickname : null) ?? (order.makerPhone?.isNotEmpty == true ? order.makerPhone : null) ?? 'U')[0].toUpperCase(),
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: isBuyAction ? _green : _red,
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        order.makerNickname ?? _maskPhone(order.makerPhone ?? ''),
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: AppColors.textPrimaryOf(context),
                        ),
                      ),
                      if (isMyOrder)
                        const Text(
                          '我的广告',
                          style: TextStyle(fontSize: 12, color: _orange),
                        ),
                    ],
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: (isBuyAction ? _green : _red).withOpacity(isDark ? 0.2 : 0.1),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    isBuyAction ? '购买' : '出售',
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                      color: isBuyAction ? _green : _red,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            // 价格和数量
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('单价', style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context))),
                      const SizedBox(height: 4),
                      Text(
                        '${formatCompact(order.price)} 绿积分',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: AppColors.textPrimaryOf(context),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('数量', style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context))),
                      const SizedBox(height: 4),
                      Text(
                        '${formatCompact(order.quantity)} 积分值',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: AppColors.textPrimaryOf(context),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            // 总金额
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: isDark ? AppColors.backgroundOf(context) : _bgGray,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('总金额', style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context))),
                  Text(
                    '${formatCompact(order.totalAmount)} 绿积分',
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: _orange,
                    ),
                  ),
                ],
              ),
            ),
            if (order.remark != null && order.remark!.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                '备注: ${order.remark}',
                style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context)),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildMyOrderCard(BuildContext context, C2cOrderModel order, String accountSequence) {
    final isDark = AppColors.isDark(context);
    // 判断当前用户在这笔订单中的角色（买方/卖方）
    // maker 创建订单: BUY→maker是买方, SELL→maker是卖方
    // taker 接单:     BUY→taker是卖方, SELL→taker是买方
    final isMaker = order.makerAccountSequence == accountSequence;
    final isUserBuying = (isMaker && order.isBuy) || (!isMaker && order.isSell);

    return GestureDetector(
      onTap: () => context.push(Routes.c2cOrderDetail, extra: order.orderNo),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppColors.cardOf(context),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 订单类型和状态
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: (isUserBuying ? _green : _red).withOpacity(isDark ? 0.2 : 0.1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        isUserBuying ? '买入' : '卖出',
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                          color: isUserBuying ? _green : _red,
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      order.orderNo,
                      style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context)),
                    ),
                  ],
                ),
                _buildStatusBadge(context, order.status),
              ],
            ),
            const SizedBox(height: 12),
            // 价格和数量
            Row(
              children: [
                Expanded(
                  child: Text(
                    '${formatCompact(order.quantity)} 积分值',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: AppColors.textPrimaryOf(context),
                    ),
                  ),
                ),
                Text(
                  '${formatCompact(order.totalAmount)} 绿积分',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: _orange,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            // 时间 + 操作按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '创建于 ${_formatDateTime(order.createdAt)}',
                  style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context)),
                ),
                if (order.status == C2cOrderStatus.pending)
                  GestureDetector(
                    onTap: () => _handleCancelOrder(order),
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                      decoration: BoxDecoration(
                        border: Border.all(color: _red.withOpacity(0.5)),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        '取消',
                        style: TextStyle(fontSize: 12, color: _red),
                      ),
                    ),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusBadge(BuildContext context, C2cOrderStatus status) {
    final isDark = AppColors.isDark(context);
    Color bgColor;
    Color textColor;
    String text;

    switch (status) {
      case C2cOrderStatus.pending:
        bgColor = _orange.withOpacity(isDark ? 0.2 : 0.1);
        textColor = _orange;
        text = '待接单';
        break;
      case C2cOrderStatus.matched:
        bgColor = Colors.blue.withOpacity(isDark ? 0.2 : 0.1);
        textColor = Colors.blue;
        text = '待付款';
        break;
      case C2cOrderStatus.paid:
        bgColor = Colors.purple.withOpacity(isDark ? 0.2 : 0.1);
        textColor = Colors.purple;
        text = '待确认';
        break;
      case C2cOrderStatus.completed:
        bgColor = _green.withOpacity(isDark ? 0.2 : 0.1);
        textColor = _green;
        text = '已完成';
        break;
      case C2cOrderStatus.cancelled:
        bgColor = AppColors.textMutedOf(context).withOpacity(isDark ? 0.2 : 0.1);
        textColor = AppColors.textMutedOf(context);
        text = '已取消';
        break;
      case C2cOrderStatus.expired:
        bgColor = _red.withOpacity(isDark ? 0.2 : 0.1);
        textColor = _red;
        text = '已过期';
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w500,
          color: textColor,
        ),
      ),
    );
  }

  String _maskPhone(String phone) {
    if (phone.length != 11) return phone;
    return '${phone.substring(0, 3)}****${phone.substring(7)}';
  }

  String _formatDateTime(DateTime dateTime) {
    final local = dateTime.toLocal();
    return '${local.month}/${local.day} ${local.hour.toString().padLeft(2, '0')}:${local.minute.toString().padLeft(2, '0')}';
  }

  // #13 + #15: 接单对话框（支持部分成交数量输入 + BUY单收款信息输入）
  void _showTakeOrderDialog(C2cOrderModel order, bool isBuyAction) {
    final caps = ref.read(capabilitiesProvider).valueOrNull ?? CapabilityMap.defaultAll();
    if (!caps.c2cEnabled) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('您的C2C交易功能已被限制'), backgroundColor: _red),
      );
      return;
    }
    final quantityController = TextEditingController(text: order.quantity);
    final paymentAccountController = TextEditingController();
    final paymentRealNameController = TextEditingController();
    final isTakingBuyOrder = order.isBuy; // 接BUY单 = taker是卖方
    // 卖方接单时获取自己的可用积分值余额
    final user = ref.read(userNotifierProvider);
    final assetAsync = ref.read(accountAssetProvider(user.accountSequence ?? ''));
    final myAvailableCash = assetAsync.valueOrNull?.availableCash ?? '0';
    Set<String> selectedPaymentMethods = {'GREEN_POINTS'};

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: AppColors.cardOf(context),
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (sheetContext) {
        return StatefulBuilder(
          builder: (context, setSheetState) {
            return Padding(
              padding: EdgeInsets.only(
                left: 20,
                right: 20,
                top: 20,
                bottom: MediaQuery.of(context).viewInsets.bottom + 20,
              ),
              child: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Center(
                      child: Text(
                        isBuyAction ? '确认购买' : '确认出售',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: AppColors.textPrimaryOf(context),
                        ),
                      ),
                    ),
                    const SizedBox(height: 20),

                    // 订单信息
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: _bgGray,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('单价', style: TextStyle(fontSize: 13, color: AppColors.textSecondaryOf(context))),
                              Text('${formatCompact(order.price)} 绿积分', style: TextStyle(fontSize: 13, color: AppColors.textPrimaryOf(context))),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('可用数量', style: TextStyle(fontSize: 13, color: AppColors.textSecondaryOf(context))),
                              Text('${formatCompact(isTakingBuyOrder ? myAvailableCash : order.quantity)} 积分值', style: TextStyle(fontSize: 13, color: AppColors.textPrimaryOf(context))),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('订单数量', style: TextStyle(fontSize: 13, color: AppColors.textSecondaryOf(context))),
                              Text('${formatCompact(order.quantity)} 积分值', style: TextStyle(fontSize: 13, color: AppColors.textPrimaryOf(context))),
                            ],
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 16),

                    // #13: 数量输入框（支持部分成交）
                    Text(
                      '交易数量',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: AppColors.textPrimaryOf(context),
                      ),
                    ),
                    const SizedBox(height: 8),
                    TextField(
                      controller: quantityController,
                      keyboardType: const TextInputType.numberWithOptions(decimal: true),
                      decoration: InputDecoration(
                        hintText: '输入数量 (最大 ${order.quantity})',
                        hintStyle: TextStyle(color: AppColors.textSecondaryOf(context)),
                        filled: true,
                        fillColor: _bgGray,
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                          borderSide: BorderSide.none,
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                          borderSide: const BorderSide(color: _orange, width: 2),
                        ),
                        suffixText: '积分值',
                        suffixStyle: TextStyle(color: AppColors.textSecondaryOf(context), fontSize: 14),
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '最小数量: 1，可输入小于订单总量的数量进行部分成交',
                      style: TextStyle(fontSize: 11, color: AppColors.textMutedOf(context)),
                    ),

                    // #15: 收款信息（仅当接BUY单时显示 — taker是卖方，需要提供收款信息）
                    if (isTakingBuyOrder) ...[
                      const SizedBox(height: 20),
                      const Divider(),
                      const SizedBox(height: 12),
                      Text(
                        '收款信息',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: AppColors.textPrimaryOf(context),
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '买方将通过以下方式向您支付绿积分',
                        style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context)),
                      ),
                      const SizedBox(height: 12),

                      // 收款方式选择
                      Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children: [
                          _buildPaymentChip('GREEN_POINTS', '绿积分', Icons.eco,
                            isSelected: selectedPaymentMethods.contains('GREEN_POINTS'),
                            isLocked: true,
                            onTap: null,
                          ),
                          _buildPaymentChip('ALIPAY', '支付宝', Icons.account_balance_wallet,
                            isSelected: selectedPaymentMethods.contains('ALIPAY'),
                            onTap: () => setSheetState(() {
                              if (selectedPaymentMethods.contains('ALIPAY')) {
                                selectedPaymentMethods.remove('ALIPAY');
                              } else {
                                selectedPaymentMethods.add('ALIPAY');
                              }
                            }),
                          ),
                          _buildPaymentChip('WECHAT', '微信', Icons.chat_bubble,
                            isSelected: selectedPaymentMethods.contains('WECHAT'),
                            onTap: () => setSheetState(() {
                              if (selectedPaymentMethods.contains('WECHAT')) {
                                selectedPaymentMethods.remove('WECHAT');
                              } else {
                                selectedPaymentMethods.add('WECHAT');
                              }
                            }),
                          ),
                          _buildPaymentChip('BANK', '银行卡', Icons.credit_card,
                            isSelected: selectedPaymentMethods.contains('BANK'),
                            onTap: () => setSheetState(() {
                              if (selectedPaymentMethods.contains('BANK')) {
                                selectedPaymentMethods.remove('BANK');
                              } else {
                                selectedPaymentMethods.add('BANK');
                              }
                            }),
                          ),
                        ],
                      ),

                      // 账户ID (自动填充)
                      const SizedBox(height: 12),
                      Text(
                        '您的账户ID（买方将向此ID转账绿积分）',
                        style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context)),
                      ),
                      const SizedBox(height: 4),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                        decoration: BoxDecoration(
                          color: _bgGray,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          ref.read(userNotifierProvider).accountSequence ?? '',
                          style: TextStyle(fontSize: 14, color: AppColors.textPrimaryOf(context)),
                        ),
                      ),

                      // 其他支付方式的收款账号
                      if (selectedPaymentMethods.any((m) => m != 'GREEN_POINTS')) ...[
                        const SizedBox(height: 12),
                        TextField(
                          controller: paymentAccountController,
                          decoration: InputDecoration(
                            labelText: '收款账号（其他支付方式）',
                            hintText: '请输入收款账号',
                            hintStyle: TextStyle(color: AppColors.textSecondaryOf(context)),
                            filled: true,
                            fillColor: _bgGray,
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: BorderSide.none,
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: const BorderSide(color: _orange, width: 2),
                            ),
                          ),
                        ),
                        const SizedBox(height: 12),
                        TextField(
                          controller: paymentRealNameController,
                          decoration: InputDecoration(
                            labelText: '收款人姓名',
                            hintText: '请输入收款人真实姓名',
                            hintStyle: TextStyle(color: AppColors.textSecondaryOf(context)),
                            filled: true,
                            fillColor: _bgGray,
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: BorderSide.none,
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: const BorderSide(color: _orange, width: 2),
                            ),
                          ),
                        ),
                      ],
                    ],

                    const SizedBox(height: 24),

                    // 提示信息
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: _orange.withOpacity(0.05),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        isBuyAction
                            ? '您将使用绿积分购买对方的积分值'
                            : '您将出售积分值，买方将向您支付绿积分',
                        style: TextStyle(fontSize: 12, color: AppColors.textSecondaryOf(context)),
                      ),
                    ),

                    const SizedBox(height: 16),

                    // 按钮
                    Row(
                      children: [
                        Expanded(
                          child: OutlinedButton(
                            onPressed: () => Navigator.pop(context),
                            style: OutlinedButton.styleFrom(
                              padding: const EdgeInsets.symmetric(vertical: 14),
                              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                            ),
                            child: const Text('取消'),
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: () {
                              if (isTakingBuyOrder) {
                                final hasOtherMethods = selectedPaymentMethods.any((m) => m != 'GREEN_POINTS');
                                String effectiveAccount;
                                String effectiveRealName;

                                if (hasOtherMethods) {
                                  effectiveAccount = paymentAccountController.text.trim();
                                  effectiveRealName = paymentRealNameController.text.trim();
                                  if (effectiveAccount.isEmpty) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(content: Text('请填写收款账号')),
                                    );
                                    return;
                                  }
                                  if (effectiveRealName.isEmpty) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(content: Text('请填写收款人姓名')),
                                    );
                                    return;
                                  }
                                } else {
                                  // 仅绿积分：使用账户ID作为收款信息
                                  final user = ref.read(userNotifierProvider);
                                  effectiveAccount = user.accountSequence ?? '';
                                  effectiveRealName = user.nickname ?? user.accountSequence ?? '';
                                }

                                Navigator.pop(context);
                                _takeOrder(
                                  order,
                                  quantity: quantityController.text.trim(),
                                  paymentMethod: selectedPaymentMethods.join(','),
                                  paymentAccount: effectiveAccount,
                                  paymentRealName: effectiveRealName,
                                );
                              } else {
                                Navigator.pop(context);
                                _takeOrder(
                                  order,
                                  quantity: quantityController.text.trim(),
                                );
                              }
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: _orange,
                              foregroundColor: Colors.white,
                              padding: const EdgeInsets.symmetric(vertical: 14),
                              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                            ),
                            child: const Text('确认接单', style: TextStyle(fontWeight: FontWeight.bold)),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildPaymentChip(String value, String label, IconData icon, {
    required bool isSelected,
    bool isLocked = false,
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: isLocked ? null : onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
        decoration: BoxDecoration(
          color: isSelected ? (value == 'GREEN_POINTS' ? _green : _orange) : _bgGray,
          borderRadius: BorderRadius.circular(8),
          border: isSelected ? null : Border.all(color: Colors.grey.shade300),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              isSelected ? Icons.check_circle : Icons.circle_outlined,
              size: 16,
              color: isSelected ? Colors.white : _grayText,
            ),
            const SizedBox(width: 4),
            Icon(icon, size: 14, color: isSelected ? Colors.white : _grayText),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(
                fontSize: 12,
                color: isSelected ? Colors.white : _darkText,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            if (isLocked) ...[
              const SizedBox(width: 2),
              Icon(Icons.lock, size: 10, color: isSelected ? Colors.white70 : _grayText),
            ],
          ],
        ),
      ),
    );
  }

  Future<void> _handleCancelOrder(C2cOrderModel order) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认取消'),
        content: const Text('确定要取消此订单吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx, false),
            child: const Text('暂不'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(ctx, true),
            child: Text('确认取消', style: TextStyle(color: _red)),
          ),
        ],
      ),
    );
    if (confirmed != true) return;

    final notifier = ref.read(c2cTradingNotifierProvider.notifier);
    final success = await notifier.cancelOrder(order.orderNo);

    if (success && mounted) {
      ref.invalidate(myC2cOrdersProvider);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('订单已取消'), backgroundColor: _green),
      );
    } else if (mounted) {
      final error = ref.read(c2cTradingNotifierProvider).error;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('取消失败: ${error ?? '未知错误'}'),
          backgroundColor: _red,
        ),
      );
    }
  }

  Future<void> _takeOrder(
    C2cOrderModel order, {
    String? quantity,
    String? paymentMethod,
    String? paymentAccount,
    String? paymentRealName,
  }) async {
    final notifier = ref.read(c2cTradingNotifierProvider.notifier);
    final success = await notifier.takeOrder(
      order.orderNo,
      quantity: quantity,
      paymentMethod: paymentMethod,
      paymentAccount: paymentAccount,
      paymentRealName: paymentRealName,
    );

    if (success && mounted) {
      // 刷新列表
      ref.invalidate(c2cOrdersProvider(order.isBuy ? 'BUY' : 'SELL'));
      ref.invalidate(myC2cOrdersProvider);

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('接单成功，请按提示完成交易'),
          backgroundColor: _green,
        ),
      );

      // 跳转到订单详情
      context.push(Routes.c2cOrderDetail, extra: order.orderNo);
    } else if (mounted) {
      final error = ref.read(c2cTradingNotifierProvider).error;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('接单失败: ${error ?? '未知错误'}'),
          backgroundColor: _red,
        ),
      );
    }
  }
}
