import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:provider/provider.dart';
import '../../../providers/asset_provider.dart';
import '../../../data/models/order_models.dart';

/// 充提订单页面
class FundOrdersPage extends StatefulWidget {
  const FundOrdersPage({super.key});

  @override
  State<FundOrdersPage> createState() => _FundOrdersPageState();
}

class _FundOrdersPageState extends State<FundOrdersPage> {
  int _activeTab = 0; // 0=全部, 1=充值, 2=提现

  // 颜色常量
  static const upColor = Color(0xFF00C853);
  static const downColor = Color(0xFFFF5252);

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadData();
    });
  }

  void _loadData() {
    final type = _activeTab == 0 ? null : _activeTab;
    context.read<AssetProvider>().loadFundOrders(type: type);
  }

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);

    return Scaffold(
      backgroundColor: theme.colorScheme.background,
      appBar: AppBar(
        title: const Text('充提记录'),
        backgroundColor: theme.colorScheme.background,
        elevation: 0,
      ),
      body: Column(
        children: [
          _buildTabs(),
          Expanded(child: _buildOrderList()),
        ],
      ),
    );
  }

  Widget _buildTabs() {
    final theme = ShadTheme.of(context);

    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          _buildTab('全部', 0),
          const SizedBox(width: 12),
          _buildTab('充值', 1),
          const SizedBox(width: 12),
          _buildTab('提现', 2),
        ],
      ),
    );
  }

  Widget _buildTab(String label, int index) {
    final theme = ShadTheme.of(context);
    final isActive = _activeTab == index;

    return Expanded(
      child: GestureDetector(
        onTap: () {
          if (_activeTab != index) {
            setState(() => _activeTab = index);
            _loadData();
          }
        },
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
            color: isActive ? theme.colorScheme.primary : theme.colorScheme.card,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(
              color: isActive ? theme.colorScheme.primary : theme.colorScheme.border,
            ),
          ),
          child: Center(
            child: Text(
              label,
              style: TextStyle(
                color: isActive ? Colors.white : theme.colorScheme.mutedForeground,
                fontWeight: isActive ? FontWeight.w600 : FontWeight.normal,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildOrderList() {
    return Consumer<AssetProvider>(
      builder: (context, provider, _) {
        final orders = provider.fundOrders;
        final isLoading = provider.isLoadingOrders;

        if (isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        if (orders.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  LucideIcons.inbox,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  '暂无订单记录',
                  style: TextStyle(color: Colors.grey[600]),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: () async => _loadData(),
          child: ListView.separated(
            padding: const EdgeInsets.all(16),
            itemCount: orders.length,
            separatorBuilder: (_, __) => const SizedBox(height: 12),
            itemBuilder: (context, index) {
              return _buildOrderCard(orders[index]);
            },
          ),
        );
      },
    );
  }

  Widget _buildOrderCard(OrderFund order) {
    final theme = ShadTheme.of(context);
    final isDeposit = order.isDeposit;

    return ShadCard(
      padding: const EdgeInsets.all(16),
      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: isDeposit
                          ? upColor.withValues(alpha: 0.1)
                          : downColor.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      order.typeText,
                      style: TextStyle(
                        color: isDeposit ? upColor : downColor,
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  _buildStatusBadge(order),
                ],
              ),
              Text(
                order.orderNo,
                style: const TextStyle(fontSize: 11, color: Colors.grey),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '${isDeposit ? '+' : '-'}${order.amount} USDT',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: isDeposit ? upColor : downColor,
                ),
              ),
              if (order.canCancel || order.canConfirmPay)
                Row(
                  children: [
                    if (order.canConfirmPay)
                      ShadButton.outline(
                        size: ShadButtonSize.sm,
                        onPressed: () => _confirmPay(order),
                        child: const Text('已打款'),
                      ),
                    if (order.canCancel) ...[
                      const SizedBox(width: 8),
                      ShadButton.destructive(
                        size: ShadButtonSize.sm,
                        onPressed: () => _cancelOrder(order),
                        child: const Text('取消'),
                      ),
                    ],
                  ],
                ),
            ],
          ),
          const SizedBox(height: 12),
          // 显示地址信息
          if (order.walletAddress != null) ...[
            const Divider(),
            const SizedBox(height: 8),
            Row(
              children: [
                Text(
                  '${isDeposit ? '充值地址' : '提现地址'}: ',
                  style: const TextStyle(fontSize: 12, color: Colors.grey),
                ),
                Expanded(
                  child: Text(
                    order.walletAddress!,
                    style: const TextStyle(fontSize: 11, fontFamily: 'monospace'),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    Clipboard.setData(ClipboardData(text: order.walletAddress!));
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('地址已复制')),
                    );
                  },
                  child: Icon(LucideIcons.copy, size: 14, color: Colors.grey[600]),
                ),
              ],
            ),
          ],
          if (order.withdrawContact != null) ...[
            const SizedBox(height: 4),
            Text(
              '联系方式: ${order.withdrawContact}',
              style: const TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '创建: ${_formatTime(order.createTime)}',
                style: const TextStyle(fontSize: 11, color: Colors.grey),
              ),
              if (order.rejectReason != null)
                Expanded(
                  child: Text(
                    '驳回: ${order.rejectReason}',
                    style: const TextStyle(fontSize: 11, color: downColor),
                    textAlign: TextAlign.right,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatusBadge(OrderFund order) {
    Color bgColor;
    Color textColor;

    // 根据类型和状态设置颜色
    if (order.type == 1) {
      // 充值状态
      switch (order.status) {
        case 1: // 待付款
        case 2: // 待确认
          bgColor = Colors.orange.withValues(alpha: 0.1);
          textColor = Colors.orange;
          break;
        case 3: // 已完成
          bgColor = upColor.withValues(alpha: 0.1);
          textColor = upColor;
          break;
        default: // 已驳回/已取消
          bgColor = downColor.withValues(alpha: 0.1);
          textColor = downColor;
      }
    } else {
      // 提现状态
      switch (order.status) {
        case 1: // 待审批
          bgColor = Colors.orange.withValues(alpha: 0.1);
          textColor = Colors.orange;
          break;
        case 2: // 已完成
          bgColor = upColor.withValues(alpha: 0.1);
          textColor = upColor;
          break;
        default: // 已驳回/已取消
          bgColor = downColor.withValues(alpha: 0.1);
          textColor = downColor;
      }
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        order.statusText,
        style: TextStyle(fontSize: 11, color: textColor),
      ),
    );
  }

  String _formatTime(DateTime? time) {
    if (time == null) return '-';
    return '${time.year}-${time.month.toString().padLeft(2, '0')}-${time.day.toString().padLeft(2, '0')} '
        '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
  }

  void _confirmPay(OrderFund order) async {
    final confirmed = await showShadDialog<bool>(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: const Text('确认已打款'),
        description: const Text('确认您已完成向指定地址的转账？'),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.pop(context, false),
          ),
          ShadButton(
            child: const Text('确认'),
            onPressed: () => Navigator.pop(context, true),
          ),
        ],
      ),
    );

    if (confirmed == true && mounted) {
      final response = await context.read<AssetProvider>().confirmPay(order.orderNo);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(response.success ? '确认成功，请等待审核' : response.message ?? '确认失败')),
        );
      }
    }
  }

  void _cancelOrder(OrderFund order) async {
    final confirmed = await showShadDialog<bool>(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: const Text('取消订单'),
        description: Text('确定要取消订单 ${order.orderNo} 吗？'),
        actions: [
          ShadButton.outline(
            child: const Text('返回'),
            onPressed: () => Navigator.pop(context, false),
          ),
          ShadButton.destructive(
            child: const Text('确定取消'),
            onPressed: () => Navigator.pop(context, true),
          ),
        ],
      ),
    );

    if (confirmed == true && mounted) {
      final response = await context.read<AssetProvider>().cancelOrder(order.orderNo);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(response.success ? '订单已取消' : response.message ?? '取消失败')),
        );
      }
    }
  }
}
