import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/wallet_service.dart';
import '../../../../routes/route_paths.dart';

/// 提款网络枚举
enum WithdrawNetwork { kava, bsc }

/// 提款参数
class WithdrawUsdtParams {
  final double amount;
  final String address;
  final WithdrawNetwork network;

  WithdrawUsdtParams({
    required this.amount,
    required this.address,
    required this.network,
  });
}

/// USDT 提款页面
/// 支持选择 KAVA 或 BSC 网络进行 USDT 提款
class WithdrawUsdtPage extends ConsumerStatefulWidget {
  const WithdrawUsdtPage({super.key});

  @override
  ConsumerState<WithdrawUsdtPage> createState() => _WithdrawUsdtPageState();
}

class _WithdrawUsdtPageState extends ConsumerState<WithdrawUsdtPage> {
  /// 提款地址控制器
  final TextEditingController _addressController = TextEditingController();

  /// 提款金额控制器
  final TextEditingController _amountController = TextEditingController();

  /// 当前选中的网络
  WithdrawNetwork _selectedNetwork = WithdrawNetwork.kava;

  /// USDT 余额
  double _usdtBalance = 0.0;

  /// 是否正在加载
  bool _isLoading = true;

  /// 钱包是否已就绪
  bool _isWalletReady = false;

  /// 手续费配置
  FeeConfig? _feeConfig;

  /// 最小提款金额
  final double _minAmount = 5.0;

  @override
  void initState() {
    super.initState();
    _loadWalletData();
  }

  @override
  void dispose() {
    _addressController.dispose();
    _amountController.dispose();
    super.dispose();
  }

  /// 加载钱包数据
  Future<void> _loadWalletData() async {
    try {
      debugPrint('[WithdrawUsdtPage] 开始加载钱包数据...');

      setState(() {
        _isLoading = true;
      });

      // 获取用户账户序列号
      final accountService = ref.read(accountServiceProvider);
      final userSerialNum = await accountService.getUserSerialNum();

      if (userSerialNum == null || userSerialNum.isEmpty) {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
        return;
      }

      // 检查钱包状态
      try {
        final walletInfo = await accountService.getWalletInfo(userSerialNum);
        _isWalletReady = walletInfo.isReady;
        debugPrint('[WithdrawUsdtPage] 钱包状态: ${walletInfo.status}, isReady: $_isWalletReady');
      } catch (e) {
        debugPrint('[WithdrawUsdtPage] 获取钱包状态失败: $e');
        _isWalletReady = false;
      }

      // 如果钱包已就绪，查询余额和手续费配置
      if (_isWalletReady) {
        try {
          final walletService = ref.read(walletServiceProvider);

          // 并行加载余额和手续费配置
          final results = await Future.wait([
            walletService.getMyWallet(),
            walletService.getFeeConfig(),
          ]);

          final wallet = results[0] as WalletResponse;
          final feeConfig = results[1] as FeeConfig;

          if (mounted) {
            setState(() {
              _usdtBalance = wallet.balances.usdt.available;
              _feeConfig = feeConfig;
              _isLoading = false;
            });
            debugPrint('[WithdrawUsdtPage] USDT 余额: $_usdtBalance');
            debugPrint('[WithdrawUsdtPage] 手续费配置: ${feeConfig.description}');
          }
        } catch (e, stackTrace) {
          debugPrint('[WithdrawUsdtPage] 加载余额失败: $e');
          debugPrint('[WithdrawUsdtPage] 堆栈: $stackTrace');
          if (mounted) {
            setState(() {
              _isLoading = false;
            });
          }
        }
      } else {
        // 钱包未就绪
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    } catch (e, stackTrace) {
      debugPrint('[WithdrawUsdtPage] 加载数据失败: $e');
      debugPrint('[WithdrawUsdtPage] 堆栈: $stackTrace');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 返回上一页
  void _goBack() {
    context.pop();
  }

  /// 选择网络
  void _selectNetwork(WithdrawNetwork network) {
    setState(() {
      _selectedNetwork = network;
    });
  }

  /// 设置全部金额（扣除手续费后的最大可转金额）
  void _setMaxAmount() {
    double maxAmount;
    if (_feeConfig != null) {
      maxAmount = _feeConfig!.calculateMaxAmount(_usdtBalance);
    } else {
      // 默认固定 2 绿积分手续费
      maxAmount = _usdtBalance - 2;
    }
    // 确保金额不为负
    if (maxAmount < 0) maxAmount = 0;
    _amountController.text = maxAmount.toStringAsFixed(2);
    setState(() {});
  }

  /// 计算手续费
  double _calculateFee() {
    final amount = double.tryParse(_amountController.text) ?? 0;
    if (_feeConfig != null) {
      return _feeConfig!.calculateFee(amount);
    }
    // 默认固定 2 绿积分
    return 2;
  }

  /// 计算实际到账（接收方收到完整金额，手续费由发送方额外承担）
  double _calculateActualAmount() {
    final amount = double.tryParse(_amountController.text) ?? 0;
    return amount;
  }

  /// 验证并提交
  void _onSubmit() {
    final address = _addressController.text.trim();
    final amountText = _amountController.text.trim();

    // 验证地址
    if (address.isEmpty) {
      _showErrorSnackBar('请输入接收账号');
      return;
    }

    // 验证地址格式
    if (!_isValidAddress(address)) {
      _showErrorSnackBar('请输入有效的充值用户ID');
      return;
    }

    // 验证金额
    if (amountText.isEmpty) {
      _showErrorSnackBar('请输入绿积分数量');
      return;
    }

    final amount = double.tryParse(amountText);
    if (amount == null || amount <= 0) {
      _showErrorSnackBar('请输入有效的金额');
      return;
    }

    if (amount < _minAmount) {
      _showErrorSnackBar('最小提取数量为 $_minAmount 绿积分');
      return;
    }

    if (amount > _usdtBalance) {
      _showErrorSnackBar('余额不足');
      return;
    }

    // 跳转到确认页面
    context.push(
      RoutePaths.withdrawConfirm,
      extra: WithdrawUsdtParams(
        amount: amount,
        address: address,
        network: _selectedNetwork,
      ),
    );
  }

  /// 验证地址格式
  bool _isValidAddress(String address) {
    // 支持两种格式：
    // 1. accountSequence 格式：D + 日期(6位) + 序号(5位)，共12位，如 D25121400005
    // 2. 区块链地址格式

    // 检查是否为 accountSequence 格式
    if (_isAccountSequence(address)) {
      return true;
    }

    // 检查区块链地址格式
    if (_selectedNetwork == WithdrawNetwork.kava) {
      // KAVA 地址格式：kava1... 或 0x...
      return address.startsWith('kava1') ||
             (address.startsWith('0x') && address.length == 42);
    } else {
      // BSC 地址格式：0x...
      return address.startsWith('0x') && address.length == 42;
    }
  }

  /// 检查是否为 accountSequence 格式
  /// 格式：D + 日期(6位) + 序号(5位)，共12位，如 D25121400005
  bool _isAccountSequence(String address) {
    if (address.length != 12) return false;
    if (!address.startsWith('D')) return false;
    // 检查后面11位是否都是数字
    final numericPart = address.substring(1);
    return RegExp(r'^\d{11}$').hasMatch(numericPart);
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  /// 打开二维码扫描页面
  Future<void> _openQrScanner() async {
    final result = await Navigator.of(context).push<String>(
      MaterialPageRoute(
        builder: (context) => const _AddressQrScannerPage(),
      ),
    );
    if (result != null && result.isNotEmpty) {
      // 从扫描结果中提取地址
      final address = _extractAddress(result);
      setState(() {
        _addressController.text = address;
      });
    }
  }

  /// 从扫描结果中提取地址
  /// 支持以下格式:
  /// - 纯地址: 0x1234... 或 kava1...
  /// - EIP-681 格式: ethereum:0x1234...
  /// - 带参数: ethereum:0x1234...?value=100
  String _extractAddress(String scannedData) {
    String data = scannedData.trim();

    // 处理 EIP-681 格式 (ethereum:0x... 或 kava:kava1...)
    if (data.contains(':')) {
      final colonIndex = data.indexOf(':');
      data = data.substring(colonIndex + 1);

      // 移除可能的参数 (?value=... 或 @chainId)
      if (data.contains('?')) {
        data = data.substring(0, data.indexOf('?'));
      }
      if (data.contains('@')) {
        data = data.substring(0, data.indexOf('@'));
      }
    }

    return data.trim();
  }

  /// 格式化数字（添加千分位）
  String _formatNumber(double number) {
    final parts = number.toStringAsFixed(2).split('.');
    final intPart = parts[0].replaceAllMapped(
      RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
      (Match m) => '${m[1]},',
    );
    return '$intPart.${parts[1]}';
  }

  /// 获取网络名称
  String _getNetworkName(WithdrawNetwork network) {
    switch (network) {
      case WithdrawNetwork.kava:
        return 'KAVA';
      case WithdrawNetwork.bsc:
        return 'BSC (BNB Chain)';
    }
  }

  /// 获取网络描述
  String _getNetworkDescription(WithdrawNetwork network) {
    switch (network) {
      case WithdrawNetwork.kava:
        return 'Kava安全网络';
      case WithdrawNetwork.bsc:
        return 'BNB Smart Chain 网络';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF5E6),
              Color(0xFFFFE4B5),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),
              // 内容区域
              Expanded(
                child: _isLoading
                    ? const Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                        ),
                      )
                    : !_isWalletReady
                        ? _buildWalletNotReadyView()
                        : SingleChildScrollView(
                            padding: const EdgeInsets.all(16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // 余额卡片
                                _buildBalanceCard(),
                                const SizedBox(height: 24),

                                // 隐藏网络选择（保留原有功能）
                                // _buildNetworkSelector(),
                                // const SizedBox(height: 24),

                                // 提款地址
                                _buildAddressInput(),
                                const SizedBox(height: 24),

                                // 提款金额
                                _buildAmountInput(),
                                const SizedBox(height: 16),

                                // 手续费信息
                                _buildFeeInfo(),
                                const SizedBox(height: 32),

                                // 提交按钮
                                _buildSubmitButton(),
                                const SizedBox(height: 16),

                                // 注意事项
                                _buildNotice(),
                              ],
                            ),
                          ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建钱包未就绪视图
  Widget _buildWalletNotReadyView() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const SizedBox(
              width: 48,
              height: 48,
              child: CircularProgressIndicator(
                strokeWidth: 3,
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
              ),
            ),
            const SizedBox(height: 24),
            const Text(
              '账号审核中...',
              style: TextStyle(
                fontSize: 20,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w600,
                color: Color(0xFF5D4037),
              ),
            ),
            const SizedBox(height: 12),
            const Text(
              '您的账号正在审核中，审核通过后即可使用提取功能',
              style: TextStyle(
                fontSize: 14,
                fontFamily: 'Inter',
                color: Color(0xFF8B5A2B),
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),
            GestureDetector(
              onTap: _loadWalletData,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                decoration: BoxDecoration(
                  color: const Color(0xFFD4AF37),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Text(
                  '刷新状态',
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildAppBar() {
    return Container(
      height: 64,
      padding: const EdgeInsets.only(top: 16, left: 16, right: 16),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _goBack,
            child: Container(
              width: 48,
              height: 48,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back,
                size: 24,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          // 标题
          const Expanded(
            child: Text(
              '提取绿积分',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
          ),
          // 占位
          const SizedBox(width: 48),
        ],
      ),
    );
  }

  /// 构建余额卡片
  Widget _buildBalanceCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '可用余额',
            style: TextStyle(
              fontSize: 14,
              fontFamily: 'Inter',
              color: Color(0xFF745D43),
            ),
          ),
          const SizedBox(height: 8),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Flexible(
                child: FittedBox(
                  fit: BoxFit.scaleDown,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    _formatNumber(_usdtBalance),
                    style: const TextStyle(
                      fontSize: 32,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w700,
                      height: 1.2,
                      color: Color(0xFF5D4037),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              const Padding(
                padding: EdgeInsets.only(bottom: 4),
                child: Text(
                  '绿积分',
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF8B5A2B),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建网络选择器
  Widget _buildNetworkSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '选择网络',
          style: TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 12),
        _buildNetworkOption(WithdrawNetwork.kava),
        // TODO: BSC 网络暂时屏蔽，待开放后取消注释
        // const SizedBox(height: 12),
        // _buildNetworkOption(WithdrawNetwork.bsc),
      ],
    );
  }

  /// 构建网络选项
  Widget _buildNetworkOption(WithdrawNetwork network) {
    final isSelected = _selectedNetwork == network;
    return GestureDetector(
      onTap: () => _selectNetwork(network),
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: isSelected ? const Color(0x1AD4AF37) : const Color(0x80FFFFFF),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isSelected ? const Color(0xFFD4AF37) : const Color(0x33D4AF37),
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Row(
          children: [
            // 选中图标
            Container(
              width: 24,
              height: 24,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: isSelected ? const Color(0xFFD4AF37) : const Color(0xFF8B5A2B),
                  width: 2,
                ),
                color: isSelected ? const Color(0xFFD4AF37) : Colors.transparent,
              ),
              child: isSelected
                  ? const Icon(
                      Icons.check,
                      size: 16,
                      color: Colors.white,
                    )
                  : null,
            ),
            const SizedBox(width: 12),
            // 网络信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _getNetworkName(network),
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w600,
                      color: isSelected ? const Color(0xFF5D4037) : const Color(0xFF745D43),
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    _getNetworkDescription(network),
                    style: const TextStyle(
                      fontSize: 12,
                      fontFamily: 'Inter',
                      color: Color(0xFF8B5A2B),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建地址输入
  Widget _buildAddressInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '接收账号',
          style: TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 12),
        Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: const Color(0x80FFFFFF),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: const Color(0x80FFFFFF),
              width: 1,
            ),
            boxShadow: const [
              BoxShadow(
                color: Color(0x0D000000),
                blurRadius: 2,
                offset: Offset(0, 1),
              ),
            ],
          ),
          child: TextField(
            controller: _addressController,
            style: const TextStyle(
              fontSize: 14,
              fontFamily: 'Inter',
              height: 1.4,
              color: Color(0xFF5D4037),
            ),
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.all(16),
              border: InputBorder.none,
              hintText: '请输入充值用户ID',
              hintStyle: const TextStyle(
                fontSize: 14,
                fontFamily: 'Inter',
                height: 1.4,
                color: Color(0x995D4037),
              ),
              suffixIcon: IconButton(
                icon: const Icon(
                  Icons.qr_code_scanner,
                  color: Color(0xFF8B5A2B),
                  size: 22,
                ),
                onPressed: _openQrScanner,
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建金额输入
  Widget _buildAmountInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text(
              '绿积分提取数量',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w600,
                color: Color(0xFF5D4037),
              ),
            ),
            GestureDetector(
              onTap: _setMaxAmount,
              child: const Text(
                '全部',
                style: TextStyle(
                  fontSize: 14,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w600,
                  color: Color(0xFFD4AF37),
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: const Color(0x80FFFFFF),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: const Color(0x80FFFFFF),
              width: 1,
            ),
            boxShadow: const [
              BoxShadow(
                color: Color(0x0D000000),
                blurRadius: 2,
                offset: Offset(0, 1),
              ),
            ],
          ),
          child: TextField(
            controller: _amountController,
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')),
            ],
            onChanged: (value) => setState(() {}),
            style: const TextStyle(
              fontSize: 18,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w600,
              height: 1.4,
              color: Color(0xFF5D4037),
            ),
            decoration: const InputDecoration(
              contentPadding: EdgeInsets.all(16),
              border: InputBorder.none,
              hintText: '请输入绿积分数量',
              hintStyle: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.4,
                color: Color(0x995D4037),
              ),
              suffixText: '绿积分',
              suffixStyle: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                color: Color(0xFF8B5A2B),
              ),
            ),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '最小提取数量: $_minAmount 绿积分',
          style: const TextStyle(
            fontSize: 12,
            fontFamily: 'Inter',
            color: Color(0xFF8B5A2B),
          ),
        ),
      ],
    );
  }

  /// 构建手续费信息
  Widget _buildFeeInfo() {
    final fee = _calculateFee();
    final actual = _calculateActualAmount();

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF5E6),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          _buildFeeRow('手续费率', '${((_feeConfig?.feeValue ?? 0.02) * 100).toStringAsFixed(1)}%'),
          const SizedBox(height: 8),
          _buildFeeRow('手续费', '${fee.toStringAsFixed(2)} 绿积分'),
          const Divider(color: Color(0x33D4AF37), height: 24),
          _buildFeeRow(
            '预计到账',
            '${actual > 0 ? actual.toStringAsFixed(2) : '0.00'} 绿积分',
            isHighlight: true,
          ),
        ],
      ),
    );
  }

  /// 构建手续费行
  Widget _buildFeeRow(String label, String value, {bool isHighlight = false}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: isHighlight ? 16 : 14,
            fontFamily: 'Inter',
            fontWeight: isHighlight ? FontWeight.w600 : FontWeight.normal,
            color: const Color(0xFF745D43),
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: isHighlight ? 18 : 14,
            fontFamily: 'Inter',
            fontWeight: isHighlight ? FontWeight.w700 : FontWeight.w500,
            color: isHighlight ? const Color(0xFFD4AF37) : const Color(0xFF5D4037),
          ),
        ),
      ],
    );
  }

  /// 构建提交按钮
  Widget _buildSubmitButton() {
    final amount = double.tryParse(_amountController.text) ?? 0;
    final isValid = _addressController.text.isNotEmpty &&
                    amount >= _minAmount &&
                    amount <= _usdtBalance;

    return GestureDetector(
      onTap: isValid ? _onSubmit : null,
      child: Container(
        width: double.infinity,
        height: 56,
        decoration: BoxDecoration(
          color: isValid ? const Color(0xFFD4AF37) : const Color(0x80D4AF37),
          borderRadius: BorderRadius.circular(12),
          boxShadow: isValid
              ? const [
                  BoxShadow(
                    color: Color(0x4DD4AF37),
                    blurRadius: 14,
                    offset: Offset(0, 4),
                  ),
                ]
              : null,
        ),
        child: const Center(
          child: Text(
            '下一步',
            style: TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w700,
              height: 1.5,
              letterSpacing: 0.24,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建注意事项
  Widget _buildNotice() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x1AFF9800),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x33FF9800),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: const [
              Icon(
                Icons.warning_amber_rounded,
                size: 20,
                color: Color(0xFFFF9800),
              ),
              SizedBox(width: 8),
              Text(
                '注意事项',
                style: TextStyle(
                  fontSize: 14,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w600,
                  color: Color(0xFFE65100),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          _buildNoticeItem('请确保接收账号正确，错误账号将导致资产丢失'),
          _buildNoticeItem('请选择正确的网络，不同网络之间不可互转'),
          _buildNoticeItem('提取需要进行手机短信验证'),
          _buildNoticeItem('提取通常在 1-30 分钟内到账'),
        ],
      ),
    );
  }

  /// 构建注意事项项
  Widget _buildNoticeItem(String text) {
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '• ',
            style: TextStyle(
              fontSize: 12,
              fontFamily: 'Inter',
              color: Color(0xFF8B5A2B),
            ),
          ),
          Expanded(
            child: Text(
              text,
              style: const TextStyle(
                fontSize: 12,
                fontFamily: 'Inter',
                color: Color(0xFF8B5A2B),
                height: 1.5,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// 地址二维码扫描页面
class _AddressQrScannerPage extends StatefulWidget {
  const _AddressQrScannerPage();

  @override
  State<_AddressQrScannerPage> createState() => _AddressQrScannerPageState();
}

class _AddressQrScannerPageState extends State<_AddressQrScannerPage> {
  MobileScannerController? _controller;
  bool _hasScanned = false;
  bool _torchOn = false;
  bool _isProcessingImage = false;

  @override
  void initState() {
    super.initState();
    _controller = MobileScannerController(
      detectionSpeed: DetectionSpeed.normal,
      facing: CameraFacing.back,
    );
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  void _onDetect(BarcodeCapture capture) {
    if (_hasScanned) return;

    final List<Barcode> barcodes = capture.barcodes;
    for (final barcode in barcodes) {
      if (barcode.rawValue != null && barcode.rawValue!.isNotEmpty) {
        _hasScanned = true;
        Navigator.of(context).pop(barcode.rawValue);
        return;
      }
    }
  }

  Future<void> _toggleTorch() async {
    await _controller?.toggleTorch();
    setState(() {
      _torchOn = !_torchOn;
    });
  }

  /// 从相册选择图片并扫描二维码
  Future<void> _pickImageAndScan() async {
    if (_isProcessingImage || _hasScanned) return;

    setState(() {
      _isProcessingImage = true;
    });

    try {
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);

      if (image == null) {
        setState(() {
          _isProcessingImage = false;
        });
        return;
      }

      // 使用 MobileScannerController 分析图片
      final BarcodeCapture? result = await _controller?.analyzeImage(image.path);

      if (result != null && result.barcodes.isNotEmpty) {
        for (final barcode in result.barcodes) {
          if (barcode.rawValue != null && barcode.rawValue!.isNotEmpty) {
            _hasScanned = true;
            if (mounted) {
              Navigator.of(context).pop(barcode.rawValue);
            }
            return;
          }
        }
      }

      // 未识别到二维码
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '未能识别图片中的二维码，请重新选择',
              style: TextStyle(fontSize: 14.sp),
            ),
            backgroundColor: const Color(0xFF6F6354),
            behavior: SnackBarBehavior.floating,
            margin: EdgeInsets.all(16.w),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8.r),
            ),
          ),
        );
      }
    } catch (e) {
      debugPrint('扫描图片失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '图片扫描失败，请重试',
              style: TextStyle(fontSize: 14.sp),
            ),
            backgroundColor: Colors.red,
            behavior: SnackBarBehavior.floating,
            margin: EdgeInsets.all(16.w),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8.r),
            ),
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isProcessingImage = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          '扫描充值ID',
          style: TextStyle(
            fontSize: 18.sp,
            color: Colors.white,
          ),
        ),
        centerTitle: true,
        actions: [
          IconButton(
            icon: Icon(
              _torchOn ? Icons.flash_on : Icons.flash_off,
              color: Colors.white,
            ),
            onPressed: _toggleTorch,
          ),
        ],
      ),
      body: Stack(
        children: [
          // 扫描区域
          MobileScanner(
            controller: _controller,
            onDetect: _onDetect,
          ),
          // 扫描框遮罩
          _buildScanOverlay(),
          // 底部区域：提示文字和相册按钮
          Positioned(
            bottom: 60.h,
            left: 0,
            right: 0,
            child: Column(
              children: [
                Text(
                  '将充值ID二维码放入框内',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.white70,
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 32.h),
                // 相册按钮
                GestureDetector(
                  onTap: _isProcessingImage ? null : _pickImageAndScan,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
                    decoration: BoxDecoration(
                      color: Colors.white.withValues(alpha: 0.15),
                      borderRadius: BorderRadius.circular(24.r),
                      border: Border.all(
                        color: Colors.white.withValues(alpha: 0.3),
                        width: 1,
                      ),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        if (_isProcessingImage)
                          SizedBox(
                            width: 18.sp,
                            height: 18.sp,
                            child: const CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          )
                        else
                          Icon(
                            Icons.photo_library_outlined,
                            size: 18.sp,
                            color: Colors.white,
                          ),
                        SizedBox(width: 8.w),
                        Text(
                          _isProcessingImage ? '识别中...' : '从相册选择',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建扫描框遮罩
  Widget _buildScanOverlay() {
    return LayoutBuilder(
      builder: (context, constraints) {
        final scanAreaSize = 250.w;
        final left = (constraints.maxWidth - scanAreaSize) / 2;
        final top = (constraints.maxHeight - scanAreaSize) / 2 - 50.h;

        return Stack(
          children: [
            // 半透明背景
            ColorFiltered(
              colorFilter: ColorFilter.mode(
                Colors.black.withValues(alpha: 0.6),
                BlendMode.srcOut,
              ),
              child: Stack(
                children: [
                  Container(
                    decoration: const BoxDecoration(
                      color: Colors.black,
                      backgroundBlendMode: BlendMode.dstOut,
                    ),
                  ),
                  Positioned(
                    left: left,
                    top: top,
                    child: Container(
                      width: scanAreaSize,
                      height: scanAreaSize,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 扫描框边角
            Positioned(
              left: left,
              top: top,
              child: _buildCorner(true, true),
            ),
            Positioned(
              right: left,
              top: top,
              child: _buildCorner(false, true),
            ),
            Positioned(
              left: left,
              bottom: constraints.maxHeight - top - scanAreaSize,
              child: _buildCorner(true, false),
            ),
            Positioned(
              right: left,
              bottom: constraints.maxHeight - top - scanAreaSize,
              child: _buildCorner(false, false),
            ),
          ],
        );
      },
    );
  }

  /// 构建边角装饰
  Widget _buildCorner(bool isLeft, bool isTop) {
    return SizedBox(
      width: 24.w,
      height: 24.w,
      child: CustomPaint(
        painter: _CornerPainter(
          isLeft: isLeft,
          isTop: isTop,
          color: const Color(0xFFD4AF37),
          strokeWidth: 3.w,
        ),
      ),
    );
  }
}

/// 边角绘制器
class _CornerPainter extends CustomPainter {
  final bool isLeft;
  final bool isTop;
  final Color color;
  final double strokeWidth;

  _CornerPainter({
    required this.isLeft,
    required this.isTop,
    required this.color,
    required this.strokeWidth,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    final path = Path();

    if (isLeft && isTop) {
      path.moveTo(0, size.height);
      path.lineTo(0, 0);
      path.lineTo(size.width, 0);
    } else if (!isLeft && isTop) {
      path.moveTo(0, 0);
      path.lineTo(size.width, 0);
      path.lineTo(size.width, size.height);
    } else if (isLeft && !isTop) {
      path.moveTo(0, 0);
      path.lineTo(0, size.height);
      path.lineTo(size.width, size.height);
    } else {
      path.moveTo(0, size.height);
      path.lineTo(size.width, size.height);
      path.lineTo(size.width, 0);
    }

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
