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 'package:qr_flutter/qr_flutter.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/storage/storage_keys.dart';

/// 充值 USDT 页面
/// 显示用户ID（accountSequence）二维码作为充值地址
/// 后端通过 accountSequence 映射到实际区块链地址
class DepositUsdtPage extends ConsumerStatefulWidget {
  const DepositUsdtPage({super.key});

  @override
  ConsumerState<DepositUsdtPage> createState() => _DepositUsdtPageState();
}

class _DepositUsdtPageState extends ConsumerState<DepositUsdtPage> {
  /// 是否正在加载
  bool _isLoading = true;

  /// USDT 余额
  String _balance = '0.00';

  /// 用户账户序列号（作为充值地址显示）
  String? _accountSequence;

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

  /// 是否显示真实钱包地址（隐藏模式）
  bool _showRealAddress = false;

  /// 真实钱包地址（KAVA）
  String? _realWalletAddress;

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

  /// 错误信息
  String? _errorMessage;

  /// 加载数据
  Future<void> _loadData() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

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

      if (userSerialNum == null || userSerialNum.isEmpty) {
        if (mounted) {
          setState(() {
            _errorMessage = '无法获取用户信息，请重新登录';
            _isLoading = false;
          });
        }
        return;
      }

      _accountSequence = userSerialNum;

      // 先从本地存储检查钱包状态
      final secureStorage = ref.read(secureStorageProvider);
      final cachedWalletReady = await secureStorage.read(key: StorageKeys.isWalletReady);

      if (cachedWalletReady == 'true') {
        // 本地已标记为 ready，直接使用
        debugPrint('[DepositUsdtPage] 本地存储显示钱包已就绪');
        _isWalletReady = true;
      } else {
        // 本地未标记，调用API检查
        try {
          final walletInfo = await accountService.getWalletInfo(userSerialNum);
          _isWalletReady = walletInfo.isReady;
          debugPrint('[DepositUsdtPage] 钱包状态: ${walletInfo.status}, isReady: $_isWalletReady');

          // 如果API返回ready，保存到本地存储
          if (_isWalletReady) {
            await secureStorage.write(key: StorageKeys.isWalletReady, value: 'true');
          }
        } catch (e) {
          debugPrint('[DepositUsdtPage] 获取钱包状态失败: $e');
          _isWalletReady = false;
        }
      }

      // 如果钱包已就绪，查询余额和真实钱包地址
      if (_isWalletReady) {
        try {
          final walletService = ref.read(walletServiceProvider);
          final walletResponse = await walletService.getMyWallet();

          // 从服务器 API 获取真实钱包地址（用于隐藏模式）
          // 不使用本地存储，避免显示其他用户的地址
          String? kavaAddress;
          try {
            final meResponse = await accountService.getMe();
            // 从 walletAddresses 中找到 KAVA 链的地址
            for (final addr in meResponse.walletAddresses) {
              if (addr.chainType.toUpperCase() == 'KAVA') {
                kavaAddress = addr.address;
                break;
              }
            }
            debugPrint('[DepositUsdtPage] 从服务器获取 KAVA 地址: $kavaAddress');
          } catch (e) {
            debugPrint('[DepositUsdtPage] 获取钱包地址失败: $e');
          }

          // 显示 USDT 可用余额
          if (mounted) {
            setState(() {
              _balance = walletResponse.balances.usdt.available.toStringAsFixed(2);
              _realWalletAddress = kavaAddress;
              _isLoading = false;
            });
          }
        } catch (e) {
          debugPrint('查询余额失败: $e');
          if (mounted) {
            setState(() {
              _balance = '0.00';
              _isLoading = false;
            });
          }
        }
      } else {
        // 钱包未就绪
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    } catch (e) {
      debugPrint('加载数据失败: $e');
      if (mounted) {
        setState(() {
          _errorMessage = '加载失败，请重试';
          _isLoading = false;
        });
      }
    }
  }

  /// 获取充值地址（根据模式返回ID或真实地址）
  String get _depositAddress {
    if (_showRealAddress && _realWalletAddress != null) {
      return _realWalletAddress!;
    }
    return _accountSequence ?? '';
  }

  /// 获取显示标题
  String get _addressTitle {
    return _showRealAddress ? '钱包地址 (KAVA)' : '充值ID';
  }

  /// 复制地址到剪贴板
  void _copyAddress() {
    if (_depositAddress.isEmpty) return;

    Clipboard.setData(ClipboardData(text: _depositAddress));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(_showRealAddress ? '钱包地址已复制' : '充值ID已复制'),
        backgroundColor: const Color(0xFFD4AF37),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  /// 切换到真实地址模式
  void _switchToRealAddressMode() {
    if (_realWalletAddress == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('钱包地址暂不可用'),
          backgroundColor: Color(0xFF8B5A2B),
          duration: Duration(seconds: 2),
        ),
      );
      return;
    }

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

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('已切换到钱包地址模式'),
        backgroundColor: Color(0xFFD4AF37),
        duration: Duration(seconds: 2),
      ),
    );
  }

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

  /// 完成充值
  void _onDepositComplete() {
    // 返回上一页
    context.pop();

    // 显示提示
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('充值确认中，请稍候查看余额变化'),
        backgroundColor: Color(0xFFD4AF37),
        duration: Duration(seconds: 3),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        // 渐变背景
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF7E6),
              Color(0xFFEAE0C8),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),
              // 内容区域
              Expanded(
                child: _isLoading
                    ? const Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                        ),
                      )
                    : !_isWalletReady
                        ? _buildWalletNotReadyView()
                        : SingleChildScrollView(
                            child: Column(
                              children: [
                                // 余额显示
                                _buildBalanceSection(),
                                const SizedBox(height: 16),
                                // 二维码卡片
                                _buildQrCodeCard(),
                                // 警告提示
                                _buildWarningText(),
                              ],
                            ),
                          ),
              ),
              // 底部按钮（只有钱包就绪时显示）
              if (!_isLoading && _isWalletReady) _buildBottomButton(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建钱包未就绪视图
  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: _loadData,
              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(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF5E6).withValues(alpha: 0.8),
      ),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _goBack,
            child: Container(
              width: 40,
              height: 40,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back,
                color: Color(0xFF5D4037),
                size: 24,
              ),
            ),
          ),
          // 标题
          const Expanded(
            child: Text(
              '充值 绿积分',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w700,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
          ),
          // 占位
          const SizedBox(width: 40),
        ],
      ),
    );
  }

  /// 构建余额显示区域
  Widget _buildBalanceSection() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: FittedBox(
        fit: BoxFit.scaleDown,
        alignment: Alignment.centerLeft,
        child: Text(
          '可用余额: $_balance 绿积分',
          style: TextStyle(
            fontSize: 14,
            fontFamily: 'Inter',
            height: 1.5,
            color: const Color(0xFF5D4037).withValues(alpha: 0.8),
          ),
        ),
      ),
    );
  }

  /// 构建二维码卡片
  Widget _buildQrCodeCard() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.5),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          // 二维码区域（长按10秒切换到真实地址模式）
          _buildQrCodeWithLongPress(),
          const SizedBox(height: 24),
          // 地址信息
          _buildAddressInfo(),
        ],
      ),
    );
  }

  /// 长按计时器
  DateTime? _longPressStartTime;

  /// 构建带长按检测的二维码
  Widget _buildQrCodeWithLongPress() {
    // 如果已经在显示真实地址，不需要长按检测
    if (_showRealAddress) {
      return _buildQrCode();
    }

    return GestureDetector(
      onLongPressStart: (_) {
        _longPressStartTime = DateTime.now();
      },
      onLongPressEnd: (_) {
        if (_longPressStartTime != null) {
          final duration = DateTime.now().difference(_longPressStartTime!);
          if (duration.inSeconds >= 10) {
            _switchToRealAddressMode();
          }
        }
        _longPressStartTime = null;
      },
      onLongPressCancel: () {
        _longPressStartTime = null;
      },
      child: _buildQrCode(),
    );
  }

  /// 构建二维码
  Widget _buildQrCode() {
    // 加载中
    if (_isLoading) {
      return Container(
        width: 192,
        height: 192,
        decoration: BoxDecoration(
          color: const Color(0xFF1A1A2E),
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Center(
          child: CircularProgressIndicator(
            color: Colors.white,
            strokeWidth: 2,
          ),
        ),
      );
    }

    // 错误状态
    if (_errorMessage != null) {
      return Container(
        width: 192,
        height: 192,
        decoration: BoxDecoration(
          color: const Color(0xFFFFF5E6),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: const Color(0xFFE74C3C), width: 1),
        ),
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(
                  Icons.error_outline,
                  color: Color(0xFFE74C3C),
                  size: 40,
                ),
                const SizedBox(height: 8),
                Text(
                  _errorMessage!,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFFE74C3C),
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),
                GestureDetector(
                  onTap: _loadData,
                  child: const Text(
                    '点击重试',
                    style: TextStyle(
                      fontSize: 12,
                      color: Color(0xFFD4AF37),
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }

    // 地址为空
    if (_depositAddress.isEmpty) {
      return Container(
        width: 192,
        height: 192,
        decoration: BoxDecoration(
          color: const Color(0xFFFFF5E6),
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Center(
          child: Text(
            '暂无充值ID',
            style: TextStyle(
              fontSize: 14,
              color: Color(0xFF5D4037),
            ),
          ),
        ),
      );
    }

    return Container(
      width: 192,
      height: 192,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 10,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: QrImageView(
          data: _depositAddress,
          version: QrVersions.auto,
          size: 192,
          backgroundColor: Colors.white,
          padding: const EdgeInsets.all(12),
          eyeStyle: const QrEyeStyle(
            eyeShape: QrEyeShape.square,
            color: Color(0xFF1A1A2E),
          ),
          dataModuleStyle: const QrDataModuleStyle(
            dataModuleShape: QrDataModuleShape.square,
            color: Color(0xFF1A1A2E),
          ),
        ),
      ),
    );
  }

  /// 构建地址信息
  Widget _buildAddressInfo() {
    // 根据模式调整字体大小（钱包地址较长，需要更小的字体）
    final addressFontSize = _showRealAddress ? 12.0 : 20.0;
    final addressLetterSpacing = _showRealAddress ? 0.5 : 1.5;

    return Column(
      children: [
        // 标题（根据模式显示不同文字）
        Text(
          _addressTitle,
          style: const TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w700,
            height: 1.25,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 12),
        // 地址文本
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Text(
            _isLoading ? '加载中...' : _depositAddress,
            style: TextStyle(
              fontSize: addressFontSize,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w600,
              height: 1.5,
              letterSpacing: addressLetterSpacing,
              color: const Color(0xFF5D4037).withValues(alpha: 0.9),
            ),
            textAlign: TextAlign.center,
          ),
        ),
        const SizedBox(height: 20),
        // 复制按钮
        GestureDetector(
          onTap: _isLoading ? null : _copyAddress,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),
            decoration: BoxDecoration(
              color: const Color(0xFFD4AF37).withValues(alpha: 0.2),
              borderRadius: BorderRadius.circular(9999),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  _showRealAddress ? '复制地址' : '复制ID',
                  style: TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    height: 1.5,
                    color: _isLoading
                        ? const Color(0xFFB0A090)
                        : const Color(0xFF745D43),
                  ),
                ),
                const SizedBox(width: 8),
                Icon(
                  Icons.copy_outlined,
                  size: 18,
                  color: _isLoading
                      ? const Color(0xFFB0A090)
                      : const Color(0xFF745D43),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建警告文字
  Widget _buildWarningText() {
    final warningText = _showRealAddress
        ? '请向此 KAVA 网络地址转入 USDT'
        : '请使用此充值ID进行充值';

    return Container(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 48),
      child: Text(
        warningText,
        style: TextStyle(
          fontSize: 12,
          fontFamily: 'Inter',
          height: 1.5,
          color: const Color(0xFFF97316).withValues(alpha: 0.8),
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  /// 构建底部按钮
  Widget _buildBottomButton() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
      child: GestureDetector(
        onTap: _onDepositComplete,
        child: Container(
          width: double.infinity,
          height: 55,
          decoration: BoxDecoration(
            color: const Color(0xFFD4AF37),
            borderRadius: BorderRadius.circular(12),
            boxShadow: const [
              BoxShadow(
                color: Color(0x4DD4AF37),
                blurRadius: 14,
                offset: Offset(0, 4),
              ),
            ],
          ),
          child: const Center(
            child: Text(
              '我已完成充值',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w700,
                height: 1.5,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
