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 '../../../data/models/c2c_order_model.dart';
import '../../providers/c2c_providers.dart';
import '../../providers/user_providers.dart';
import '../../providers/asset_providers.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: _bgGray,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: _darkText),
          onPressed: () => context.pop(),
        ),
        title: const Text(
          'C2C交易',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: _darkText,
          ),
        ),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.add_circle_outline, color: _orange),
            onPressed: () => context.push(Routes.c2cPublish),
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          labelColor: _orange,
          unselectedLabelColor: _grayText,
          indicatorColor: _orange,
          indicatorWeight: 3,
          tabs: const [
            Tab(text: '购买'),
            Tab(text: '出售'),
            Tab(text: '我的'),
          ],
        ),
      ),
      body: Column(
        children: [
          // 资产概览
          _buildAssetOverview(asset),
          // 订单列表
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildOrderList('SELL'), // 购买页面显示卖单
                _buildOrderList('BUY'),  // 出售页面显示买单
                _buildMyOrderList(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAssetOverview(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: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '可用积分股',
                  style: TextStyle(fontSize: 12, color: _grayText),
                ),
                const SizedBox(height: 4),
                Text(
                  formatAmount(availableShares),
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: _orange,
                  ),
                ),
              ],
            ),
          ),
          Container(width: 1, height: 40, color: _bgGray),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '可用积分值',
                    style: TextStyle(fontSize: 12, color: _grayText),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    formatAmount(availableCash),
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: _green,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildOrderList(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: [
            const Icon(Icons.error_outline, size: 48, color: _grayText),
            const SizedBox(height: 8),
            Text('加载失败', style: TextStyle(color: _grayText)),
            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: _grayText.withOpacity(0.5)),
                const SizedBox(height: 16),
                Text(
                  type == 'SELL' ? '暂无出售广告' : '暂无购买广告',
                  style: TextStyle(fontSize: 16, color: _grayText),
                ),
                const SizedBox(height: 8),
                Text(
                  '点击右上角发布广告',
                  style: TextStyle(fontSize: 14, color: _grayText.withOpacity(0.7)),
                ),
              ],
            ),
          );
        }

        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(order, type == 'SELL');
            },
          ),
        );
      },
    );
  }

  Widget _buildMyOrderList() {
    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: [
            const Icon(Icons.error_outline, size: 48, color: _grayText),
            const SizedBox(height: 8),
            Text('加载失败', style: TextStyle(color: _grayText)),
          ],
        ),
      ),
      data: (ordersPage) {
        final orders = ordersPage.data;
        if (orders.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.history, size: 64, color: _grayText.withOpacity(0.5)),
                const SizedBox(height: 16),
                Text(
                  '暂无订单记录',
                  style: TextStyle(fontSize: 16, color: _grayText),
                ),
              ],
            ),
          );
        }

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

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

    return GestureDetector(
      onTap: isMyOrder ? null : () => _showTakeOrderDialog(order, isBuyAction),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          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(0.1),
                  ),
                  child: Center(
                    child: Text(
                      (order.makerNickname ?? order.makerPhone ?? '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: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: _darkText,
                        ),
                      ),
                      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(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: [
                      const Text('单价', style: TextStyle(fontSize: 12, color: _grayText)),
                      const SizedBox(height: 4),
                      Text(
                        '${formatPrice(order.price)} 积分值',
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: _darkText,
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text('数量', style: TextStyle(fontSize: 12, color: _grayText)),
                      const SizedBox(height: 4),
                      Text(
                        '${formatAmount(order.quantity)} 积分股',
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: _darkText,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            // 总金额
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: _bgGray,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text('总金额', style: TextStyle(fontSize: 12, color: _grayText)),
                  Text(
                    '${formatAmount(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: _grayText),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildMyOrderCard(C2cOrderModel order) {
    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: Colors.white,
          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: (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),
                    Text(
                      order.orderNo,
                      style: const TextStyle(fontSize: 12, color: _grayText),
                    ),
                  ],
                ),
                _buildStatusBadge(order.status),
              ],
            ),
            const SizedBox(height: 12),
            // 价格和数量
            Row(
              children: [
                Expanded(
                  child: Text(
                    '${formatAmount(order.quantity)} 积分股',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: _darkText,
                    ),
                  ),
                ),
                Text(
                  '${formatAmount(order.totalAmount)} 积分值',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: _orange,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            // 时间
            Text(
              '创建于 ${_formatDateTime(order.createdAt)}',
              style: const TextStyle(fontSize: 12, color: _grayText),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusBadge(C2cOrderStatus status) {
    Color bgColor;
    Color textColor;
    String text;

    switch (status) {
      case C2cOrderStatus.pending:
        bgColor = _orange.withOpacity(0.1);
        textColor = _orange;
        text = '待接单';
        break;
      case C2cOrderStatus.matched:
        bgColor = Colors.blue.withOpacity(0.1);
        textColor = Colors.blue;
        text = '待付款';
        break;
      case C2cOrderStatus.paid:
        bgColor = Colors.purple.withOpacity(0.1);
        textColor = Colors.purple;
        text = '待确认';
        break;
      case C2cOrderStatus.completed:
        bgColor = _green.withOpacity(0.1);
        textColor = _green;
        text = '已完成';
        break;
      case C2cOrderStatus.cancelled:
        bgColor = _grayText.withOpacity(0.1);
        textColor = _grayText;
        text = '已取消';
        break;
      case C2cOrderStatus.expired:
        bgColor = _red.withOpacity(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) {
    return '${dateTime.month}/${dateTime.day} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  void _showTakeOrderDialog(C2cOrderModel order, bool isBuyAction) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(isBuyAction ? '确认购买' : '确认出售'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('数量: ${formatAmount(order.quantity)} 积分股'),
            const SizedBox(height: 8),
            Text('单价: ${formatPrice(order.price)} 积分值'),
            const SizedBox(height: 8),
            Text(
              '总金额: ${formatAmount(order.totalAmount)} 积分值',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            Text(
              isBuyAction
                  ? '您将使用积分值购买对方的积分股'
                  : '您将出售积分股换取对方的积分值',
              style: TextStyle(fontSize: 12, color: _grayText),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              await _takeOrder(order);
            },
            child: Text(
              '确认',
              style: TextStyle(color: _orange),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _takeOrder(C2cOrderModel order) async {
    final notifier = ref.read(c2cTradingNotifierProvider.notifier);
    final success = await notifier.takeOrder(order.orderNo);

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