import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../../../core/constants/app_colors.dart';
import '../../../core/utils/format_utils.dart';
import '../../../domain/entities/trade_order.dart';
import '../../../domain/entities/trade_record.dart';
import '../../../data/models/trade_order_model.dart';
import '../../providers/trading_providers.dart';

/// 交易记录页面
class TradingRecordsPage extends ConsumerStatefulWidget {
  const TradingRecordsPage({super.key});

  @override
  ConsumerState<TradingRecordsPage> createState() => _TradingRecordsPageState();
}

class _TradingRecordsPageState extends ConsumerState<TradingRecordsPage> with SingleTickerProviderStateMixin {
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _green = Color(0xFF22C55E);
  static const Color _red = Color(0xFFEF4444);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _darkText = Color(0xFF1F2937);
  static const Color _lightGray = Color(0xFF9CA3AF);

  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: _darkText, size: 20),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          '交易记录',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: _darkText,
          ),
        ),
        centerTitle: true,
        bottom: TabBar(
          controller: _tabController,
          labelColor: _orange,
          unselectedLabelColor: _grayText,
          indicatorColor: _orange,
          tabs: const [
            Tab(text: '订单记录'),
            Tab(text: '成交明细'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildOrdersTab(),
          _buildTradesTab(),
        ],
      ),
    );
  }

  // ==================== 订单记录 Tab ====================
  Widget _buildOrdersTab() {
    final ordersAsync = ref.watch(ordersProvider);

    return RefreshIndicator(
      onRefresh: () async {
        ref.invalidate(ordersProvider);
      },
      child: ordersAsync.when(
        loading: () => _buildLoadingList(),
        error: (error, stack) => _buildErrorView(error.toString(), () => ref.invalidate(ordersProvider)),
        data: (ordersPage) {
          if (ordersPage == null || ordersPage.data.isEmpty) {
            return _buildEmptyView('暂无订单记录', '前往交易页面进行买卖操作');
          }
          return _buildOrdersList(ordersPage);
        },
      ),
    );
  }

  // ==================== 成交明细 Tab ====================
  Widget _buildTradesTab() {
    final tradesAsync = ref.watch(tradesProvider);

    return RefreshIndicator(
      onRefresh: () async {
        ref.invalidate(tradesProvider);
      },
      child: tradesAsync.when(
        loading: () => _buildLoadingList(),
        error: (error, stack) => _buildErrorView(error.toString(), () => ref.invalidate(tradesProvider)),
        data: (tradesPage) {
          if (tradesPage == null || tradesPage.data.isEmpty) {
            return _buildEmptyView('暂无成交记录', '成交后将在此显示明细');
          }
          return _buildTradesList(tradesPage);
        },
      ),
    );
  }

  Widget _buildLoadingList() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: 10,
      itemBuilder: (context, index) => _buildShimmerCard(),
    );
  }

  Widget _buildShimmerCard() {
    return 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: [
              Container(
                width: 80,
                height: 24,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              Container(
                width: 60,
                height: 20,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 100,
                height: 14,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              Container(
                width: 80,
                height: 14,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildErrorView(String error, VoidCallback onRetry) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.error_outline, size: 48, color: AppColors.error),
          const SizedBox(height: 16),
          Text('加载失败', style: TextStyle(fontSize: 16, color: _grayText)),
          const SizedBox(height: 8),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32),
            child: Text(
              error,
              style: TextStyle(fontSize: 12, color: _grayText),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: onRetry,
            style: ElevatedButton.styleFrom(backgroundColor: _orange),
            child: const Text('重试', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyView(String title, String subtitle) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.receipt_long_outlined, size: 64, color: _grayText.withValues(alpha: 0.5)),
          const SizedBox(height: 16),
          Text(title, style: TextStyle(fontSize: 16, color: _grayText)),
          const SizedBox(height: 8),
          Text(subtitle, style: TextStyle(fontSize: 14, color: _grayText.withValues(alpha: 0.7))),
        ],
      ),
    );
  }

  Widget _buildOrdersList(OrdersPageModel ordersPage) {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: ordersPage.data.length + 1,
      itemBuilder: (context, index) {
        if (index == ordersPage.data.length) {
          return _buildBottomInfo('共 ${ordersPage.total} 条订单记录');
        }
        return _buildOrderCard(ordersPage.data[index]);
      },
    );
  }

  Widget _buildTradesList(TradesPageModel tradesPage) {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: tradesPage.data.length + 1,
      itemBuilder: (context, index) {
        if (index == tradesPage.data.length) {
          return _buildBottomInfo('共 ${tradesPage.total} 条成交记录');
        }
        return _buildTradeCard(tradesPage.data[index]);
      },
    );
  }

  Widget _buildOrderCard(TradeOrder order) {
    final isBuy = order.isBuy;
    final typeColor = isBuy ? _green : _red;
    final typeText = isBuy ? '买入' : '卖出';
    final statusText = _getStatusText(order.status);
    final statusColor = _getStatusColor(order.status);

    return 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: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                decoration: BoxDecoration(
                  color: typeColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  typeText,
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: typeColor),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                decoration: BoxDecoration(
                  color: statusColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  statusText,
                  style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: statusColor),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildInfoItem('价格', _formatPrice(order.price)),
              _buildInfoItem('数量', _formatQuantity(order.quantity)),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildInfoItem('已成交', '${_formatQuantity(order.filledQuantity)} / ${_formatQuantity(order.quantity)}'),
              _buildInfoItem('金额', '${_formatPrice(order.totalAmount)} 积分值'),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Row(
                  children: [
                    Text('订单号: ', style: TextStyle(fontSize: 11, color: _lightGray)),
                    Expanded(
                      child: Text(
                        order.orderNo,
                        style: TextStyle(fontSize: 11, color: _grayText, fontFamily: 'monospace'),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              Row(
                children: [
                  Icon(Icons.access_time, size: 11, color: _lightGray),
                  const SizedBox(width: 4),
                  Text(
                    DateFormat('MM-dd HH:mm').format(order.createdAt.toLocal()),
                    style: TextStyle(fontSize: 11, color: _lightGray),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTradeCard(TradeRecord trade) {
    final isBuy = trade.isBuy;
    final typeColor = isBuy ? _green : _red;
    final typeText = isBuy ? '买入' : '卖出';

    return 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: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                decoration: BoxDecoration(
                  color: typeColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  typeText,
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: typeColor),
                ),
              ),
              Text(
                DateFormat('MM-dd HH:mm').format(trade.createdAt.toLocal()),
                style: TextStyle(fontSize: 12, color: _lightGray),
              ),
            ],
          ),
          const SizedBox(height: 12),

          if (isBuy) ...[
            // 买入：显示简化信息
            _buildDetailRow('成交价格', '${_formatPrice(trade.price)} 积分值'),
            _buildDetailRow('成交数量', '${_formatQuantity(trade.quantity)} 积分股'),
            _buildDetailRow('支付总额', '${formatAmount(trade.grossAmount)} 积分值'),
          ] else ...[
            // 卖出：显示完整明细（类似确认卖出弹窗）
            _buildDetailRow('卖出数量', '${_formatQuantity(trade.originalQuantity)} 积分股'),
            _buildDetailRow('卖出价格', '${_formatPrice(trade.price)} 积分值'),
            _buildDetailRow('销毁倍数', _formatMultiplier(trade.burnMultiplier)),
            _buildDetailRow('有效积分股', _formatQuantity(trade.quantity)),
            _buildDetailRow('交易总额', '${formatAmount(trade.grossAmount)} 积分值'),
            _buildDetailRow(
              '进入积分股池',
              '${formatAmount(trade.fee)} 积分值 (10%)',
              valueColor: const Color(0xFFE67E22),
            ),
            _buildDetailRow(
              '实际获得',
              '${formatAmount(trade.netAmount)} 积分值',
              valueColor: _green,
              isBold: true,
            ),
          ],

          const SizedBox(height: 8),
          // 成交编号
          Row(
            children: [
              Text('成交编号: ', style: TextStyle(fontSize: 11, color: _lightGray)),
              Expanded(
                child: Text(
                  trade.tradeNo,
                  style: TextStyle(fontSize: 11, color: _grayText, fontFamily: 'monospace'),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, {Color? valueColor, bool isBold = false}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(fontSize: 13, color: _grayText),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: 13,
              color: valueColor ?? _darkText,
              fontWeight: isBold ? FontWeight.w600 : FontWeight.w500,
              fontFamily: 'monospace',
            ),
          ),
        ],
      ),
    );
  }

  String _formatMultiplier(String multiplier) {
    final value = double.tryParse(multiplier) ?? 1;
    return value.toStringAsFixed(4);
  }

  Widget _buildInfoItem(String label, String value, {Color? valueColor}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('$label: ', style: TextStyle(fontSize: 12, color: _grayText)),
        Text(
          value,
          style: TextStyle(
            fontSize: 12,
            color: valueColor ?? _darkText,
            fontWeight: FontWeight.w500,
            fontFamily: 'monospace',
          ),
        ),
      ],
    );
  }

  String _getStatusText(OrderStatus status) {
    switch (status) {
      case OrderStatus.pending:
        return '委托中';
      case OrderStatus.partial:
        return '部分成交';
      case OrderStatus.filled:
        return '已成交';
      case OrderStatus.cancelled:
        return '已取消';
    }
  }

  Color _getStatusColor(OrderStatus status) {
    switch (status) {
      case OrderStatus.pending:
        return _orange;
      case OrderStatus.partial:
        return Colors.blue;
      case OrderStatus.filled:
        return _green;
      case OrderStatus.cancelled:
        return _grayText;
    }
  }

  String _formatPrice(String price) {
    try {
      final value = double.parse(price);
      if (value >= 1) return value.toStringAsFixed(4);
      if (value >= 0.0001) return value.toStringAsFixed(6);
      if (value <= 0) return '0';
      // 0.00000980 → 0.0{5}980
      final str = value.toStringAsFixed(18);
      final dotIndex = str.indexOf('.');
      int zeroCount = 0;
      for (int i = dotIndex + 1; i < str.length; i++) {
        if (str[i] == '0') {
          zeroCount++;
        } else {
          break;
        }
      }
      final sigStart = dotIndex + 1 + zeroCount;
      final sigEnd = sigStart + 7 > str.length ? str.length : sigStart + 7;
      final significant = str.substring(sigStart, sigEnd);
      return '0.0{$zeroCount}$significant';
    } catch (e) {
      return price;
    }
  }

  String _formatQuantity(String quantity) {
    try {
      final value = double.parse(quantity);
      if (value == value.truncate()) {
        return value.truncate().toString();
      }
      return value.toStringAsFixed(2);
    } catch (e) {
      return quantity;
    }
  }

  Widget _buildBottomInfo(String text) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Center(
        child: Text(text, style: TextStyle(fontSize: 12, color: _grayText)),
      ),
    );
  }
}
