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 '../../../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
  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),

          const SizedBox(height: 16),

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

          const SizedBox(height: 16),

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

          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) {
    Color statusColor;
    String statusText;
    String statusDesc;
    IconData statusIcon;

    switch (order.status) {
      case C2cOrderStatus.pending:
        statusColor = _orange;
        statusText = '待接单';
        statusDesc = '等待其他用户接单...';
        statusIcon = Icons.hourglass_empty;
        break;
      case C2cOrderStatus.matched:
        statusColor = Colors.blue;
        statusText = '待付款';
        statusDesc = '买方需在规定时间内付款';
        statusIcon = Icons.payment;
        break;
      case C2cOrderStatus.paid:
        statusColor = Colors.purple;
        statusText = '待确认';
        statusDesc = '卖方需确认收款后释放资产';
        statusIcon = Icons.check_circle_outline;
        break;
      case C2cOrderStatus.completed:
        statusColor = _green;
        statusText = '已完成';
        statusDesc = '交易已完成';
        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: const TextStyle(fontSize: 14, color: _grayText),
          ),
        ],
      ),
    );
  }

  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: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: (order.isBuy ? _green : _red).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  order.typeText,
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: order.isBuy ? _green : _red,
                  ),
                ),
              ),
              const SizedBox(width: 8),
              if (isMaker)
                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,
                    ),
                  ),
                ),
            ],
          ),
          const SizedBox(height: 16),
          _buildInfoRow('订单编号', order.orderNo, 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 _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 ?? _maskPhone(order.makerPhone ?? ''),
            isMe: isMaker,
          ),
          const Divider(height: 24),
          // 接单方
          if (order.takerAccountSequence != null)
            _buildParticipantRow(
              label: order.isBuy ? '卖方 (接单者)' : '买方 (接单者)',
              name: order.takerNickname ?? _maskPhone(order.takerPhone ?? ''),
              isMe: isTaker,
            )
          else
            const Text(
              '等待接单...',
              style: TextStyle(fontSize: 14, color: _grayText),
            ),
        ],
      ),
    );
  }

  Widget _buildParticipantRow({
    required String label,
    required String name,
    required bool isMe,
  }) {
    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[0].toUpperCase(),
              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,
                        ),
                      ),
                    ),
                  ],
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

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