import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/utils/format_utils.dart';
import '../../../data/models/c2c_order_model.dart';
import '../../providers/c2c_providers.dart';
import '../../providers/user_providers.dart';
import '../../providers/asset_providers.dart';

class C2cOrderDetailPage extends ConsumerStatefulWidget {
  final String orderNo;

  const C2cOrderDetailPage({super.key, required this.orderNo});

  @override
  ConsumerState<C2cOrderDetailPage> createState() => _C2cOrderDetailPageState();
}

class _C2cOrderDetailPageState extends ConsumerState<C2cOrderDetailPage> {
  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);

  // 用于倒计时刷新
  @override
  void initState() {
    super.initState();
    // 每秒刷新一次以更新倒计时
    Future.doWhile(() async {
      await Future.delayed(const Duration(seconds: 1));
      if (mounted) {
        setState(() {});
        return true;
      }
      return false;
    });
  }

  @override
  void dispose() {
    // 离开详情页时刷新市场和我的订单列表（确保过期恢复的新订单及时显示）
    ref.invalidate(c2cOrdersProvider(null));
    ref.invalidate(c2cOrdersProvider('BUY'));
    ref.invalidate(c2cOrdersProvider('SELL'));
    ref.invalidate(myC2cOrdersProvider);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final orderAsync = ref.watch(c2cOrderDetailProvider(widget.orderNo));
    final c2cState = ref.watch(c2cTradingNotifierProvider);

    return Scaffold(
      backgroundColor: _bgGray,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: _darkText),
          onPressed: () => context.pop(),
        ),
        title: const Text(
          '订单详情',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: _darkText,
          ),
        ),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh, color: _orange),
            onPressed: () => ref.invalidate(c2cOrderDetailProvider(widget.orderNo)),
          ),
        ],
      ),
      body: orderAsync.when(
        loading: () => const Center(
          child: CircularProgressIndicator(color: _orange),
        ),
        error: (error, stack) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error_outline, size: 48, color: _grayText),
              const SizedBox(height: 8),
              Text('加载失败: $error', style: const TextStyle(color: _grayText)),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () => ref.invalidate(c2cOrderDetailProvider(widget.orderNo)),
                child: const Text('重试'),
              ),
            ],
          ),
        ),
        data: (order) => _buildContent(order, c2cState),
      ),
    );
  }

  Widget _buildContent(C2cOrderModel order, C2cTradingState c2cState) {
    final user = ref.watch(userNotifierProvider);
    final isMaker = order.makerAccountSequence == user.accountSequence;
    final isTaker = order.takerAccountSequence == user.accountSequence;
    final isBuyer = (order.isBuy && isMaker) || (order.isSell && isTaker);

    return SingleChildScrollView(
      child: Column(
        children: [
          const SizedBox(height: 16),

          // 订单状态卡片
          _buildStatusCard(order, isBuyer),

          const SizedBox(height: 16),

          // 订单信息
          _buildOrderInfoCard(order, isMaker),

          // Bot 支付信息卡片（Bot 购买的卖单显示）
          if (order.isBotPurchased)
            ...[
              const SizedBox(height: 16),
              _buildBotPaymentInfoCard(order),
            ],

          // 收款信息卡片（已匹配或已付款状态时显示）
          if (order.hasPaymentInfo &&
              (order.isMatched || order.isPaid))
            ...[
              const SizedBox(height: 16),
              _buildPaymentInfoCard(order, isBuyer),
            ],

          const SizedBox(height: 16),

          // 交易双方信息
          _buildParticipantsCard(order, isMaker, isTaker),

          // 付款水单
          if ((order.isMatched || order.isPaid || order.isCompleted) && !order.isBotPurchased)
            ...[
              const SizedBox(height: 16),
              _buildPaymentProofCard(order, isBuyer),
            ],

          const SizedBox(height: 16),

          // 操作说明
          _buildInstructionsCard(order, isMaker, isTaker, isBuyer),

          const SizedBox(height: 24),

          // 操作按钮
          _buildActionButtons(order, isMaker, isTaker, isBuyer, c2cState),

          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget _buildStatusCard(C2cOrderModel order, bool isBuyer) {
    Color statusColor;
    String statusText;
    String statusDesc;
    IconData statusIcon;
    int? remainingSeconds;

    switch (order.status) {
      case C2cOrderStatus.pending:
        statusColor = _orange;
        statusText = '待接单';
        statusDesc = '等待其他用户接单...';
        statusIcon = Icons.hourglass_empty;
        break;
      case C2cOrderStatus.matched:
        statusColor = Colors.blue;
        statusText = '待付款';
        remainingSeconds = order.paymentRemainingSeconds;
        if (isBuyer) {
          statusDesc = remainingSeconds != null && remainingSeconds > 0
              ? '你需要在 ${_formatRemainingTime(remainingSeconds)} 内完成付款'
              : '请在规定时间内完成付款';
        } else {
          statusDesc = remainingSeconds != null && remainingSeconds > 0
              ? '对方将在 ${_formatRemainingTime(remainingSeconds)} 内完成付款'
              : '买方需在规定时间内付款';
        }
        statusIcon = Icons.payment;
        break;
      case C2cOrderStatus.paid:
        statusColor = Colors.purple;
        statusText = '待确认';
        remainingSeconds = order.confirmRemainingSeconds;
        if (isBuyer) {
          statusDesc = remainingSeconds != null && remainingSeconds > 0
              ? '等待卖方在 ${_formatRemainingTime(remainingSeconds)} 内确认收款'
              : '等待卖方确认收款';
        } else {
          statusDesc = remainingSeconds != null && remainingSeconds > 0
              ? '请在 ${_formatRemainingTime(remainingSeconds)} 内确认收款'
              : '请确认收款后释放资产';
        }
        statusIcon = Icons.check_circle_outline;
        break;
      case C2cOrderStatus.completed:
        statusColor = _green;
        statusText = '已完成';
        statusDesc = order.isBotPurchased ? 'Bot 已自动购买并支付 dUSDT' : '交易已完成';
        statusIcon = Icons.verified;
        break;
      case C2cOrderStatus.cancelled:
        statusColor = _grayText;
        statusText = '已取消';
        statusDesc = '订单已取消';
        statusIcon = Icons.cancel_outlined;
        break;
      case C2cOrderStatus.expired:
        statusColor = _red;
        statusText = '已过期';
        statusDesc = '订单已过期';
        statusIcon = Icons.timer_off;
        break;
    }

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              color: statusColor.withOpacity(0.1),
              shape: BoxShape.circle,
            ),
            child: Icon(statusIcon, size: 32, color: statusColor),
          ),
          const SizedBox(height: 16),
          Text(
            statusText,
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: statusColor,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            statusDesc,
            style: TextStyle(
              fontSize: 14,
              color: remainingSeconds != null && remainingSeconds < 300
                  ? _red
                  : _grayText,
              fontWeight: remainingSeconds != null && remainingSeconds < 300
                  ? FontWeight.bold
                  : FontWeight.normal,
            ),
          ),
          // 显示倒计时进度条
          if (remainingSeconds != null && remainingSeconds > 0) ...[
            const SizedBox(height: 16),
            _buildCountdownProgress(order, remainingSeconds),
          ],
        ],
      ),
    );
  }

  Widget _buildCountdownProgress(C2cOrderModel order, int remainingSeconds) {
    final totalSeconds = order.isMatched
        ? order.paymentTimeoutMinutes * 60
        : order.confirmTimeoutMinutes * 60;
    final progress = remainingSeconds / totalSeconds;

    return Column(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: LinearProgressIndicator(
            value: progress,
            backgroundColor: _bgGray,
            valueColor: AlwaysStoppedAnimation<Color>(
              remainingSeconds < 300 ? _red : _orange,
            ),
            minHeight: 6,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '剩余时间 ${_formatRemainingTime(remainingSeconds)}',
          style: TextStyle(
            fontSize: 12,
            color: remainingSeconds < 300 ? _red : _grayText,
          ),
        ),
      ],
    );
  }

  String _formatRemainingTime(int seconds) {
    if (seconds <= 0) return '00:00';
    final minutes = seconds ~/ 60;
    final secs = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }

  Widget _buildOrderInfoCard(C2cOrderModel order, bool isMaker) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (isMaker)
            Padding(
              padding: const EdgeInsets.only(bottom: 16),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: _orange.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Text(
                  '我发布的',
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: _orange,
                  ),
                ),
              ),
            )
          else
            const SizedBox(height: 0),
          _buildInfoRow('订单编号', order.orderNo, canCopy: true),
          // 卖方收款ID（卖单=maker，买单=taker）
          if (order.isSell)
            _buildInfoRow('卖方ID', order.makerAccountSequence, canCopy: true)
          else if (order.takerAccountSequence != null)
            _buildInfoRow('卖方ID', order.takerAccountSequence!, canCopy: true),
          _buildInfoRow('单价', '${formatPrice(order.price)} 绿积分/积分值'),
          _buildInfoRow('数量', '${formatAmount(order.quantity)} 积分值'),
          _buildInfoRow('总金额', '${formatAmount(order.totalAmount)} 绿积分'),
          _buildInfoRow('创建时间', _formatDateTime(order.createdAt)),
          if (order.remark != null && order.remark!.isNotEmpty)
            _buildInfoRow('备注', order.remark!),
        ],
      ),
    );
  }

  Widget _buildPaymentInfoCard(C2cOrderModel order, bool isBuyer) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: isBuyer ? _green.withOpacity(0.05) : Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: isBuyer ? Border.all(color: _green.withOpacity(0.3)) : null,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                _getPaymentIcon(order.paymentMethod),
                size: 20,
                color: _orange,
              ),
              const SizedBox(width: 8),
              Text(
                isBuyer ? '请向以下账户付款' : '您的收款信息',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: _darkText,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          // 收款方式
          _buildPaymentInfoRow(
            label: '收款方式',
            value: order.paymentMethodText,
            icon: _getPaymentIcon(order.paymentMethod),
          ),

          // 收款账号
          if (order.paymentAccount != null)
            _buildPaymentInfoRow(
              label: '收款账号',
              value: order.paymentAccount!,
              canCopy: true,
            ),

          // 收款人姓名
          if (order.paymentRealName != null)
            _buildPaymentInfoRow(
              label: '收款人',
              value: order.paymentRealName!,
            ),

          // 卖家 Kava 地址（绿积分转账目标地址）
          if (order.sellerKavaAddress != null && isBuyer)
            _buildPaymentInfoRow(
              label: 'Kava 地址',
              value: order.sellerKavaAddress!,
              canCopy: true,
            ),

          // 付款金额
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: _orange.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '付款金额',
                  style: TextStyle(fontSize: 14, color: _grayText),
                ),
                Row(
                  children: [
                    Text(
                      formatAmount(order.totalAmount),
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: _orange,
                      ),
                    ),
                    const SizedBox(width: 4),
                    const Text(
                      '积分值',
                      style: TextStyle(fontSize: 12, color: _grayText),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // 买方提示
          if (isBuyer) ...[
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: _red.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: const [
                  Icon(Icons.warning_amber, size: 16, color: _red),
                  SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '请确保转账金额准确，转账后点击"已付款"按钮',
                      style: TextStyle(fontSize: 12, color: _red),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// Bot 支付信息卡片
  Widget _buildBotPaymentInfoCard(C2cOrderModel order) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: _green.withOpacity(0.05),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _green.withOpacity(0.3)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: const [
              Icon(Icons.smart_toy, size: 20, color: _green),
              SizedBox(width: 8),
              Text(
                'Bot 自动购买',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: _darkText,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          // 支付说明
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: _green.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: const [
                Icon(Icons.check_circle, size: 16, color: _green),
                SizedBox(width: 8),
                Expanded(
                  child: Text(
                    'Bot 已自动购买您的卖单，dUSDT 已转入您的 Kava 地址',
                    style: TextStyle(fontSize: 13, color: _darkText),
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(height: 12),

          // 收款地址
          if (order.sellerKavaAddress != null)
            _buildPaymentInfoRow(
              label: '收款地址',
              value: _truncateAddress(order.sellerKavaAddress!),
              canCopy: true,
              copyValue: order.sellerKavaAddress,
            ),

          // 支付金额
          _buildPaymentInfoRow(
            label: '支付金额',
            value: '${formatAmount(order.totalAmount)} dUSDT',
          ),

          // 交易哈希
          if (order.paymentTxHash != null)
            _buildPaymentInfoRow(
              label: '交易哈希',
              value: _truncateAddress(order.paymentTxHash!),
              canCopy: true,
              copyValue: order.paymentTxHash,
            ),

          // 查看交易链接
          if (order.paymentTxHash != null) ...[
            const SizedBox(height: 12),
            InkWell(
              onTap: () => _openExplorer(order.paymentTxHash!),
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const [
                    Icon(Icons.open_in_new, size: 16, color: _orange),
                    SizedBox(width: 4),
                    Text(
                      '在区块链浏览器中查看',
                      style: TextStyle(
                        fontSize: 13,
                        color: _orange,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 截断地址显示
  String _truncateAddress(String address) {
    if (address.length <= 16) return address;
    return '${address.substring(0, 8)}...${address.substring(address.length - 8)}';
  }

  /// 打开区块链浏览器
  Future<void> _openExplorer(String txHash) async {
    // Kava 区块链浏览器
    final url = 'https://kavascan.com/tx/$txHash';
    // 这里可以使用 url_launcher 包打开链接
    // 暂时只复制交易哈希
    Clipboard.setData(ClipboardData(text: url));
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('区块链浏览器链接已复制'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  Widget _buildPaymentInfoRow({
    required String label,
    required String value,
    IconData? icon,
    bool canCopy = false,
    String? copyValue,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(fontSize: 14, color: _grayText),
          ),
          Row(
            children: [
              if (icon != null) ...[
                Icon(icon, size: 16, color: _darkText),
                const SizedBox(width: 4),
              ],
              Text(
                value,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: _darkText,
                ),
              ),
              if (canCopy) ...[
                const SizedBox(width: 8),
                GestureDetector(
                  onTap: () {
                    Clipboard.setData(ClipboardData(text: copyValue ?? value));
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('已复制'),
                        duration: Duration(seconds: 1),
                      ),
                    );
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: _orange.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: const Text(
                      '复制',
                      style: TextStyle(fontSize: 12, color: _orange),
                    ),
                  ),
                ),
              ],
            ],
          ),
        ],
      ),
    );
  }

  IconData _getPaymentIcon(C2cPaymentMethod? method) {
    switch (method) {
      case C2cPaymentMethod.greenPoints:
        return Icons.eco;
      case C2cPaymentMethod.alipay:
        return Icons.account_balance_wallet;
      case C2cPaymentMethod.wechat:
        return Icons.chat_bubble;
      case C2cPaymentMethod.bank:
        return Icons.credit_card;
      default:
        return Icons.payment;
    }
  }

  Widget _buildInfoRow(String label, String value, {bool canCopy = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: const TextStyle(fontSize: 14, color: _grayText),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Flexible(
                  child: Text(
                    value,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: _darkText,
                    ),
                    textAlign: TextAlign.right,
                  ),
                ),
                if (canCopy) ...[
                  const SizedBox(width: 4),
                  GestureDetector(
                    onTap: () {
                      Clipboard.setData(ClipboardData(text: value));
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('已复制'),
                          duration: Duration(seconds: 1),
                        ),
                      );
                    },
                    child: const Icon(Icons.copy, size: 16, color: _grayText),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildParticipantsCard(C2cOrderModel order, bool isMaker, bool isTaker) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '交易双方',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: _darkText,
            ),
          ),
          const SizedBox(height: 16),
          // 发布方
          _buildParticipantRow(
            label: order.isBuy ? '买方 (发布者)' : '卖方 (发布者)',
            name: order.makerNickname?.isNotEmpty == true
                ? order.makerNickname!
                : (order.makerPhone?.isNotEmpty == true ? order.makerPhone! : '未知用户'),
            phone: order.makerPhone,
            isMe: isMaker,
          ),
          const Divider(height: 24),
          // 接单方
          if (order.takerAccountSequence != null)
            _buildParticipantRow(
              label: order.isBuy ? '卖方 (接单者)' : '买方 (接单者)',
              name: order.takerNickname?.isNotEmpty == true
                  ? order.takerNickname!
                  : (order.takerPhone?.isNotEmpty == true ? order.takerPhone! : '未知用户'),
              phone: order.takerPhone,
              isMe: isTaker,
            )
          else
            const Text(
              '等待接单...',
              style: TextStyle(fontSize: 14, color: _grayText),
            ),
          // 对方收款信息
          if (order.paymentAccount != null && order.takerAccountSequence != null) ...[
            const Divider(height: 24),
            _buildInfoRow('收款账号', order.paymentAccount!, canCopy: true),
            if (order.paymentRealName != null)
              _buildInfoRow('收款人', order.paymentRealName!),
          ],
        ],
      ),
    );
  }

  Widget _buildParticipantRow({
    required String label,
    required String name,
    required bool isMe,
    String? phone,
  }) {
    return Row(
      children: [
        Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: (isMe ? _orange : _grayText).withOpacity(0.1),
          ),
          child: Center(
            child: Text(
              name.isNotEmpty ? name[0].toUpperCase() : 'U',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: isMe ? _orange : _grayText,
              ),
            ),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                label,
                style: const TextStyle(fontSize: 12, color: _grayText),
              ),
              const SizedBox(height: 2),
              Row(
                children: [
                  Text(
                    name,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: _darkText,
                    ),
                  ),
                  if (isMe) ...[
                    const SizedBox(width: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: _orange.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: const Text(
                        '我',
                        style: TextStyle(
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                          color: _orange,
                        ),
                      ),
                    ),
                  ],
                ],
              ),
              if (phone != null && phone.isNotEmpty) ...[
                const SizedBox(height: 2),
                Text(
                  phone,
                  style: const TextStyle(fontSize: 12, color: _grayText),
                ),
              ],
            ],
          ),
        ),
      ],
    );
  }

  /// 将后端返回的相对路径转为完整图片 URL
  String _buildProofImageUrl(String relativePath) {
    if (relativePath.startsWith('http')) return relativePath;
    return '${AppConstants.baseUrl}$relativePath';
  }

  Widget _buildPaymentProofCard(C2cOrderModel order, bool isBuyer) {
    final hasProof = order.paymentProofUrl != null && order.paymentProofUrl!.isNotEmpty;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.receipt_long, size: 20, color: _orange),
              const SizedBox(width: 8),
              const Text(
                '付款水单',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: _darkText,
                ),
              ),
              const Spacer(),
              if (isBuyer && (order.isMatched || order.isPaid))
                GestureDetector(
                  onTap: () => _handleUploadProof(order),
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: _orange.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: const [
                        Icon(Icons.upload, size: 16, color: _orange),
                        SizedBox(width: 4),
                        Text(
                          '上传水单',
                          style: TextStyle(fontSize: 12, color: _orange, fontWeight: FontWeight.w500),
                        ),
                      ],
                    ),
                  ),
                ),
            ],
          ),
          const SizedBox(height: 16),
          if (hasProof)
            GestureDetector(
              onTap: () => _showProofFullScreen(_buildProofImageUrl(order.paymentProofUrl!)),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  _buildProofImageUrl(order.paymentProofUrl!),
                  height: 200,
                  width: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (_, __, ___) => Container(
                    height: 100,
                    color: _bgGray,
                    child: const Center(
                      child: Text('图片加载失败', style: TextStyle(color: _grayText)),
                    ),
                  ),
                ),
              ),
            )
          else
            Container(
              height: 80,
              width: double.infinity,
              decoration: BoxDecoration(
                color: _bgGray,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey.shade300, style: BorderStyle.solid),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.image_not_supported_outlined, size: 28, color: Colors.grey.shade400),
                    const SizedBox(height: 4),
                    Text(
                      isBuyer ? '请上传付款凭证' : '买方暂未上传水单',
                      style: TextStyle(fontSize: 12, color: Colors.grey.shade400),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }

  Future<void> _handleUploadProof(C2cOrderModel order) async {
    final picker = ImagePicker();
    final image = await picker.pickImage(
      source: ImageSource.gallery,
      maxWidth: 1920,
      maxHeight: 1920,
      imageQuality: 85,
    );
    if (image == null) return;

    final notifier = ref.read(c2cTradingNotifierProvider.notifier);
    final success = await notifier.uploadPaymentProof(order.orderNo, image.path);

    if (success && mounted) {
      ref.invalidate(c2cOrderDetailProvider(order.orderNo));
      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,
        ),
      );
    }
  }

  void _showProofFullScreen(String url) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.black,
        insetPadding: const EdgeInsets.all(0),
        child: Stack(
          fit: StackFit.expand,
          children: [
            InteractiveViewer(
              child: Image.network(
                url,
                fit: BoxFit.contain,
                errorBuilder: (_, __, ___) => const Center(
                  child: Text('图片加载失败', style: TextStyle(color: Colors.white)),
                ),
              ),
            ),
            Positioned(
              top: 40,
              right: 16,
              child: IconButton(
                icon: const Icon(Icons.close, color: Colors.white, size: 28),
                onPressed: () => Navigator.pop(context),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInstructionsCard(
    C2cOrderModel order,
    bool isMaker,
    bool isTaker,
    bool isBuyer,
  ) {
    if (order.status == C2cOrderStatus.completed ||
        order.status == C2cOrderStatus.cancelled ||
        order.status == C2cOrderStatus.expired) {
      return const SizedBox.shrink();
    }

    String title;
    List<String> instructions;

    switch (order.status) {
      case C2cOrderStatus.pending:
        title = '操作说明';
        instructions = isMaker
            ? ['等待其他用户接单', '您也可以取消此订单']
            : ['此订单尚未被接单'];
        break;
      case C2cOrderStatus.matched:
        title = isBuyer ? '付款说明' : '等待买方付款';
        instructions = isBuyer
            ? [
                '请通过线下方式向卖方转账',
                '转账金额: ${formatAmount(order.totalAmount)} 积分值',
                '转账完成后点击"已付款"',
                '注意: 请确保已完成转账再点击确认',
              ]
            : [
                '请等待买方完成付款',
                '买方付款后您将收到通知',
                '确认收款后请及时确认释放',
              ];
        break;
      case C2cOrderStatus.paid:
        title = isBuyer ? '等待卖方确认' : '确认收款';
        instructions = isBuyer
            ? [
                '您已确认付款',
                '请等待卖方确认收款',
                '卖方确认后积分值将自动划转到您的账户',
              ]
            : [
                '买方已确认付款',
                '请检查您是否已收到转账',
                '确认收款后积分值将自动划转给买方',
              ];
        break;
      default:
        title = '';
        instructions = [];
    }

    if (instructions.isEmpty) return const SizedBox.shrink();

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: _orange.withOpacity(0.05),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _orange.withOpacity(0.2)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.info_outline, size: 18, color: _orange),
              const SizedBox(width: 8),
              Text(
                title,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  color: _orange,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          ...instructions.map((text) => Padding(
                padding: const EdgeInsets.only(bottom: 8),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('• ', style: TextStyle(color: _grayText)),
                    Expanded(
                      child: Text(
                        text,
                        style: const TextStyle(
                          fontSize: 13,
                          color: _grayText,
                          height: 1.4,
                        ),
                      ),
                    ),
                  ],
                ),
              )),
        ],
      ),
    );
  }

  Widget _buildActionButtons(
    C2cOrderModel order,
    bool isMaker,
    bool isTaker,
    bool isBuyer,
    C2cTradingState c2cState,
  ) {
    final List<Widget> buttons = [];

    switch (order.status) {
      case C2cOrderStatus.pending:
        if (isMaker) {
          buttons.add(_buildActionButton(
            label: '取消订单',
            color: _red,
            isLoading: c2cState.isLoading,
            onPressed: () => _handleCancel(order),
          ));
        }
        break;

      case C2cOrderStatus.matched:
        if (isBuyer) {
          buttons.add(_buildActionButton(
            label: '已付款',
            color: _green,
            isLoading: c2cState.isLoading,
            onPressed: () => _handleConfirmPayment(order),
          ));
        }
        // 卖方可以取消（如果买方未付款）
        if (!isBuyer && (isMaker || isTaker)) {
          buttons.add(_buildActionButton(
            label: '取消订单',
            color: _red,
            isOutlined: true,
            isLoading: c2cState.isLoading,
            onPressed: () => _handleCancel(order),
          ));
        }
        break;

      case C2cOrderStatus.paid:
        if (!isBuyer && (isMaker || isTaker)) {
          buttons.add(_buildActionButton(
            label: '确认收款并释放',
            color: _green,
            isLoading: c2cState.isLoading,
            onPressed: () => _handleConfirmReceived(order),
          ));
        }
        break;

      case C2cOrderStatus.completed:
      case C2cOrderStatus.cancelled:
      case C2cOrderStatus.expired:
        // 已完成、已取消、已过期的订单不显示操作按钮
        break;
    }

    if (buttons.isEmpty) {
      return const SizedBox.shrink();
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        children: buttons,
      ),
    );
  }

  Widget _buildActionButton({
    required String label,
    required Color color,
    required bool isLoading,
    required VoidCallback onPressed,
    bool isOutlined = false,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: SizedBox(
        width: double.infinity,
        height: 50,
        child: isOutlined
            ? OutlinedButton(
                onPressed: isLoading ? null : onPressed,
                style: OutlinedButton.styleFrom(
                  foregroundColor: color,
                  side: BorderSide(color: color),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: isLoading
                    ? SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: color,
                        ),
                      )
                    : Text(
                        label,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
              )
            : ElevatedButton(
                onPressed: isLoading ? null : onPressed,
                style: ElevatedButton.styleFrom(
                  backgroundColor: color,
                  foregroundColor: Colors.white,
                  disabledBackgroundColor: color.withOpacity(0.4),
                  disabledForegroundColor: Colors.white70,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: isLoading
                    ? const SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: Colors.white,
                        ),
                      )
                    : Text(
                        label,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
              ),
      ),
    );
  }

  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.year}-${local.month.toString().padLeft(2, '0')}-${local.day.toString().padLeft(2, '0')} '
        '${local.hour.toString().padLeft(2, '0')}:${local.minute.toString().padLeft(2, '0')}';
  }

  Future<void> _handleCancel(C2cOrderModel order) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认取消'),
        content: const Text('确定要取消此订单吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('暂不取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, 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(c2cOrderDetailProvider(order.orderNo));
      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> _handleConfirmPayment(C2cOrderModel order) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认付款'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('请确认您已完成以下付款:'),
            const SizedBox(height: 16),
            Text('金额: ${formatAmount(order.totalAmount)} 积分值'),
            const SizedBox(height: 16),
            const Text(
              '注意：请确保已完成线下转账，虚假确认可能导致资产损失。',
              style: TextStyle(fontSize: 12, color: _red),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('暂未付款'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: Text('确认已付款', style: TextStyle(color: _green)),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

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

    if (success && mounted) {
      ref.invalidate(c2cOrderDetailProvider(order.orderNo));
      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> _handleConfirmReceived(C2cOrderModel order) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认收款'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('请确认您已收到买方的付款:'),
            const SizedBox(height: 16),
            Text('金额: ${formatAmount(order.totalAmount)} 积分值'),
            const SizedBox(height: 16),
            const Text(
              '确认后，您的积分值将自动划转给买方，此操作不可撤销。',
              style: TextStyle(fontSize: 12, color: _red),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('暂未收款'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: Text('确认收款并释放', style: TextStyle(color: _green)),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

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

    if (success && mounted) {
      ref.invalidate(c2cOrderDetailProvider(order.orderNo));
      ref.invalidate(myC2cOrdersProvider);
      // 刷新资产
      final user = ref.read(userNotifierProvider);
      ref.invalidate(accountAssetProvider(user.accountSequence ?? ''));

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