import 'dart:async';
import 'dart:io';
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:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import '../../../../routes/route_paths.dart';
import '../../../../routes/app_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/account_service.dart';

/// 备份助记词页面
/// 进入时调用 API 获取钱包信息和助记词
class BackupMnemonicPage extends ConsumerStatefulWidget {
  /// 用户序列号
  final String userSerialNum;
  /// 推荐码
  final String? referralCode;

  const BackupMnemonicPage({
    super.key,
    required this.userSerialNum,
    this.referralCode,
  });

  @override
  ConsumerState<BackupMnemonicPage> createState() => _BackupMnemonicPageState();
}

class _BackupMnemonicPageState extends ConsumerState<BackupMnemonicPage> {
  // 加载状态
  bool _isLoading = true;
  // 错误信息
  String? _errorMessage;
  // 钱包信息
  WalletInfoResponse? _walletInfo;
  // 助记词列表
  List<String> _mnemonicWords = [];
  // 钱包地址
  String? _kavaAddress;
  String? _dstAddress;
  String? _bscAddress;

  // 是否隐藏助记词
  bool _isHidden = false;
  // 是否正在下载
  bool _isDownloading = false;

  // 轮询定时器
  Timer? _pollTimer;
  // 倒计时定时器
  Timer? _countdownTimer;
  // 倒计时剩余秒数 (100秒)
  int _countdownSeconds = 100;

  @override
  void initState() {
    super.initState();
    debugPrint('[BackupMnemonicPage] initState - userSerialNum: ${widget.userSerialNum}, referralCode: ${widget.referralCode}');
    _loadWalletInfo();
  }

  @override
  void dispose() {
    debugPrint('[BackupMnemonicPage] dispose - 取消轮询定时器和倒计时');
    _pollTimer?.cancel();
    _countdownTimer?.cancel();
    super.dispose();
  }

  /// 加载钱包信息
  Future<void> _loadWalletInfo() async {
    debugPrint('[BackupMnemonicPage] _loadWalletInfo - 开始加载钱包信息, userSerialNum: ${widget.userSerialNum}');
    try {
      final accountService = ref.read(accountServiceProvider);

      // 调用 API 获取钱包信息
      debugPrint('[BackupMnemonicPage] _loadWalletInfo - 调用 accountService.getWalletInfo()');
      final response = await accountService.getWalletInfo(widget.userSerialNum);

      if (!mounted) {
        debugPrint('[BackupMnemonicPage] _loadWalletInfo - Widget已卸载，忽略响应');
        return;
      }

      debugPrint('[BackupMnemonicPage] _loadWalletInfo - 响应状态: ${response.status}, isReady: ${response.isReady}, isGenerating: ${response.isGenerating}, isFailed: ${response.isFailed}');

      if (response.isReady) {
        // 钱包已就绪
        // 处理助记词：空字符串或null都视为无助记词（MPC模式）
        final mnemonic = response.mnemonic?.trim() ?? '';
        final words = mnemonic.isEmpty ? <String>[] : mnemonic.split(' ');
        final wordCount = words.length;
        debugPrint('[BackupMnemonicPage] _loadWalletInfo - 钱包就绪! 助记词数量: $wordCount');
        debugPrint('[BackupMnemonicPage] _loadWalletInfo - KAVA: ${_maskAddress(response.walletAddresses?.kava)}');
        debugPrint('[BackupMnemonicPage] _loadWalletInfo - DST: ${_maskAddress(response.walletAddresses?.dst)}');
        debugPrint('[BackupMnemonicPage] _loadWalletInfo - BSC: ${_maskAddress(response.walletAddresses?.bsc)}');

        // MPC模式：无助记词，直接跳转到主页
        if (wordCount == 0) {
          debugPrint('[BackupMnemonicPage] _loadWalletInfo - MPC模式，无助记词，跳转到主页');
          if (mounted) {
            context.go('/home');
          }
          return;
        }

        setState(() {
          _walletInfo = response;
          _mnemonicWords = words;
          _kavaAddress = response.walletAddresses?.kava;
          _dstAddress = response.walletAddresses?.dst;
          _bscAddress = response.walletAddresses?.bsc;
          _isLoading = false;
          _errorMessage = null;
        });
      } else if (response.isGenerating) {
        // 钱包生成中，轮询等待
        debugPrint('[BackupMnemonicPage] _loadWalletInfo - 钱包生成中，开始轮询...');
        setState(() {
          _isLoading = true;
          _errorMessage = null;
        });
        _startPolling();
        _startCountdown();
      } else if (response.isFailed) {
        // 钱包生成失败
        debugPrint('[BackupMnemonicPage] _loadWalletInfo - 钱包生成失败');
        setState(() {
          _isLoading = false;
          _errorMessage = '钱包生成失败，请稍后重试';
        });
      }
    } catch (e, stackTrace) {
      debugPrint('[BackupMnemonicPage] _loadWalletInfo - 异常: $e');
      debugPrint('[BackupMnemonicPage] _loadWalletInfo - 堆栈: $stackTrace');
      if (mounted) {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${e.toString().replaceAll('Exception: ', '')}';
        });
      }
    }
  }

  /// 脱敏地址显示 (用于日志)
  String _maskAddress(String? address) {
    if (address == null || address.length < 10) return address ?? 'null';
    return '${address.substring(0, 6)}...${address.substring(address.length - 4)}';
  }

  /// 开始倒计时
  void _startCountdown() {
    _countdownTimer?.cancel();
    _countdownSeconds = 100;
    debugPrint('[BackupMnemonicPage] _startCountdown - 启动100秒倒计时');
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!mounted) {
        timer.cancel();
        return;
      }
      if (_countdownSeconds > 0) {
        setState(() {
          _countdownSeconds--;
        });
      } else {
        timer.cancel();
        debugPrint('[BackupMnemonicPage] _startCountdown - 倒计时结束');
      }
    });
  }

  /// 停止倒计时
  void _stopCountdown() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    debugPrint('[BackupMnemonicPage] _stopCountdown - 停止倒计时');
  }

  /// 开始轮询
  int _pollCount = 0;
  void _startPolling() {
    _pollTimer?.cancel();
    _pollCount = 0;
    debugPrint('[BackupMnemonicPage] _startPolling - 启动轮询定时器 (每2秒)');
    _pollTimer = Timer.periodic(const Duration(seconds: 2), (timer) async {
      _pollCount++;
      if (!mounted) {
        debugPrint('[BackupMnemonicPage] _startPolling - Widget已卸载，取消轮询');
        timer.cancel();
        return;
      }

      debugPrint('[BackupMnemonicPage] _startPolling - 第 $_pollCount 次轮询...');

      try {
        final accountService = ref.read(accountServiceProvider);
        final response = await accountService.getWalletInfo(widget.userSerialNum);

        if (!mounted) {
          debugPrint('[BackupMnemonicPage] _startPolling - Widget已卸载，忽略响应');
          return;
        }

        debugPrint('[BackupMnemonicPage] _startPolling - 轮询响应状态: ${response.status}');

        if (response.isReady) {
          debugPrint('[BackupMnemonicPage] _startPolling - 钱包就绪! 停止轮询 (共轮询 $_pollCount 次)');
          timer.cancel();
          _stopCountdown();
          // 处理助记词：空字符串或null都视为无助记词（MPC模式）
          final mnemonic = response.mnemonic?.trim() ?? '';
          final words = mnemonic.isEmpty ? <String>[] : mnemonic.split(' ');
          final wordCount = words.length;
          debugPrint('[BackupMnemonicPage] _startPolling - 助记词数量: $wordCount');

          // MPC模式：无助记词，直接跳转到主页
          if (wordCount == 0) {
            debugPrint('[BackupMnemonicPage] _startPolling - MPC模式，无助记词，跳转到主页');
            if (mounted) {
              context.go('/home');
            }
            return;
          }

          setState(() {
            _walletInfo = response;
            _mnemonicWords = words;
            _kavaAddress = response.walletAddresses?.kava;
            _dstAddress = response.walletAddresses?.dst;
            _bscAddress = response.walletAddresses?.bsc;
            _isLoading = false;
            _errorMessage = null;
          });
        } else if (response.isFailed) {
          debugPrint('[BackupMnemonicPage] _startPolling - 钱包生成失败，停止轮询');
          timer.cancel();
          _stopCountdown();
          setState(() {
            _isLoading = false;
            _errorMessage = '钱包生成失败，请稍后重试';
          });
        } else {
          debugPrint('[BackupMnemonicPage] _startPolling - 仍在生成中，继续轮询...');
        }
      } catch (e) {
        // 忽略轮询中的错误，继续尝试
        debugPrint('[BackupMnemonicPage] _startPolling - 轮询出错 (继续重试): $e');
      }
    });
  }

  /// 复制全部助记词
  void _copyAllMnemonic() {
    debugPrint('[BackupMnemonicPage] _copyAllMnemonic - 复制助记词到剪贴板');
    final mnemonicText = _mnemonicWords.join(' ');
    Clipboard.setData(ClipboardData(text: mnemonicText));
    _showCopySuccess('助记词已复制到剪贴板');
  }

  /// 复制地址
  void _copyAddress(String address, String label) {
    debugPrint('[BackupMnemonicPage] _copyAddress - 复制 $label: ${_maskAddress(address)}');
    Clipboard.setData(ClipboardData(text: address));
    _showCopySuccess('$label 已复制');
  }

  /// 显示复制成功提示
  void _showCopySuccess(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: const Color(0xFFD4AF37),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  /// 切换助记词显示/隐藏
  void _toggleVisibility() {
    setState(() {
      _isHidden = !_isHidden;
    });
  }

  /// 下载助记词备份文件
  Future<void> _downloadMnemonic() async {
    debugPrint('[BackupMnemonicPage] _downloadMnemonic - 开始下载备份文件');
    if (_isDownloading || _mnemonicWords.isEmpty) {
      debugPrint('[BackupMnemonicPage] _downloadMnemonic - 跳过: isDownloading=$_isDownloading, wordsEmpty=${_mnemonicWords.isEmpty}');
      return;
    }

    setState(() => _isDownloading = true);

    try {
      // 获取临时目录
      debugPrint('[BackupMnemonicPage] _downloadMnemonic - 获取临时目录');
      final directory = await getTemporaryDirectory();
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final file = File('${directory.path}/mnemonic_backup_$timestamp.txt');

      // 生成备份内容
      final content = '''
=====================================
      RWA 榴莲皇后 - 助记词备份
=====================================

【重要警告】
请妥善保管此文件，丢失将无法恢复账号！
请勿将助记词分享给任何人！
请将助记词抄写在纸上，离线保管！

=====================================
       您的 12 词助记词
=====================================

${_mnemonicWords.asMap().entries.map((e) => '${(e.key + 1).toString().padLeft(2, ' ')}. ${e.value}').join('\n')}

=====================================
       钱包地址信息
=====================================

KAVA 地址: ${_kavaAddress ?? 'N/A'}
DST 地址:  ${_dstAddress ?? 'N/A'}
BSC 地址:  ${_bscAddress ?? 'N/A'}
序列号:    ${widget.userSerialNum}

=====================================
       备份时间
=====================================

${DateTime.now().toString()}

=====================================
''';

      // 写入文件
      debugPrint('[BackupMnemonicPage] _downloadMnemonic - 写入文件: ${file.path}');
      await file.writeAsString(content);

      if (!mounted) return;

      // 分享文件
      debugPrint('[BackupMnemonicPage] _downloadMnemonic - 调用分享');
      await Share.shareXFiles(
        [XFile(file.path)],
        subject: 'RWA 助记词备份',
      );

      // 删除临时文件
      if (await file.exists()) {
        debugPrint('[BackupMnemonicPage] _downloadMnemonic - 删除临时文件');
        await file.delete();
      }
      debugPrint('[BackupMnemonicPage] _downloadMnemonic - 下载完成');
    } catch (e, stackTrace) {
      debugPrint('[BackupMnemonicPage] _downloadMnemonic - 下载失败: $e');
      debugPrint('[BackupMnemonicPage] _downloadMnemonic - 堆栈: $stackTrace');
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('下载失败: $e'),
          backgroundColor: const Color(0xFF991B1B),
        ),
      );
    } finally {
      if (mounted) {
        setState(() => _isDownloading = false);
      }
    }
  }

  /// 确认已备份，跳转到确认备份页面进行验证
  void _confirmBackup() {
    debugPrint('[BackupMnemonicPage] _confirmBackup - 用户点击确认备份');
    if (_mnemonicWords.isEmpty || _kavaAddress == null) {
      debugPrint('[BackupMnemonicPage] _confirmBackup - 钱包信息不完整: words=${_mnemonicWords.length}, kavaAddress=${_kavaAddress != null}');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('钱包信息不完整，请等待加载完成'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    debugPrint('[BackupMnemonicPage] _confirmBackup - 跳转到验证页面, userSerialNum: ${widget.userSerialNum}');
    // 跳转到确认备份页面
    context.push(
      RoutePaths.verifyMnemonic,
      extra: VerifyMnemonicParams(
        mnemonicWords: _mnemonicWords,
        kavaAddress: _kavaAddress!,
        dstAddress: _dstAddress!,
        bscAddress: _bscAddress!,
        userSerialNum: widget.userSerialNum,
        referralCode: widget.referralCode,
      ),
    );
  }

  /// 返回上一步
  void _goBack() {
    debugPrint('[BackupMnemonicPage] _goBack - 用户返回上一步');
    context.pop();
  }

  @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(0xFFFFF5E6),
              Color(0xFFFFE4B5),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),
              // 内容区域 - 始终显示内容，加载时覆盖蒙版
              Expanded(
                child: Stack(
                  children: [
                    // 底层：内容（始终显示，加载时显示占位数据）
                    _buildContentWithPlaceholder(),
                    // 顶层：加载蒙版或错误蒙版
                    if (_isLoading) _buildLoadingOverlay(),
                    if (_errorMessage != null) _buildErrorOverlay(),
                  ],
                ),
              ),
              // 底部按钮区域 (非加载状态且无错误时显示)
              if (!_isLoading && _errorMessage == null) _buildBottomButtons(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建加载蒙版 - 覆盖助记词和地址区域，显示倒计时
  Widget _buildLoadingOverlay() {
    return Positioned.fill(
      child: Container(
        color: const Color(0xCC5D4037), // 半透明深棕色蒙版
        child: Center(
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 32),
            padding: const EdgeInsets.all(32),
            decoration: BoxDecoration(
              color: const Color(0xFFFFFDF5),
              borderRadius: BorderRadius.circular(20),
              boxShadow: const [
                BoxShadow(
                  color: Color(0x33000000),
                  blurRadius: 20,
                  offset: Offset(0, 8),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 安全图标
                Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    color: const Color(0xFFFFF3D6),
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: const Color(0xFFD4A84B),
                      width: 3,
                    ),
                  ),
                  child: const Center(
                    child: Icon(
                      Icons.security,
                      size: 40,
                      color: Color(0xFFD4A84B),
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                // 提示文字
                const Text(
                  '正在进行钱包的安全计算',
                  style: TextStyle(
                    fontSize: 18,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w700,
                    color: Color(0xFF5D4037),
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),
                const Text(
                  '使用多方安全计算技术生成您的钱包',
                  style: TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF8B7355),
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 32),
                // 倒计时圆环
                _buildCountdownCircle(),
                const SizedBox(height: 16),
                // 倒计时文字
                Text(
                  '预计剩余 $_countdownSeconds 秒',
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF8B7355),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建倒计时圆环
  Widget _buildCountdownCircle() {
    final progress = _countdownSeconds / 100.0;
    return SizedBox(
      width: 100,
      height: 100,
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 背景圆环
          SizedBox(
            width: 100,
            height: 100,
            child: CircularProgressIndicator(
              value: 1.0,
              strokeWidth: 8,
              backgroundColor: const Color(0xFFE8E0D0),
              valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFFE8E0D0)),
            ),
          ),
          // 进度圆环
          SizedBox(
            width: 100,
            height: 100,
            child: CircularProgressIndicator(
              value: progress,
              strokeWidth: 8,
              backgroundColor: Colors.transparent,
              valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFFD4A84B)),
            ),
          ),
          // 倒计时数字
          Text(
            '$_countdownSeconds',
            style: const TextStyle(
              fontSize: 32,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w700,
              color: Color(0xFFD4A84B),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建错误蒙版
  Widget _buildErrorOverlay() {
    return Positioned.fill(
      child: Container(
        color: const Color(0xCC5D4037), // 半透明深棕色蒙版
        child: Center(
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 32),
            padding: const EdgeInsets.all(32),
            decoration: BoxDecoration(
              color: const Color(0xFFFFFDF5),
              borderRadius: BorderRadius.circular(20),
              boxShadow: const [
                BoxShadow(
                  color: Color(0x33000000),
                  blurRadius: 20,
                  offset: Offset(0, 8),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 错误图标
                Container(
                  width: 80,
                  height: 80,
                  decoration: const BoxDecoration(
                    color: Color(0xFFFFE4E4),
                    shape: BoxShape.circle,
                  ),
                  child: const Center(
                    child: Icon(
                      Icons.error_outline,
                      size: 48,
                      color: Color(0xFFCC6B2C),
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                // 错误标题
                const Text(
                  '钱包生成失败',
                  style: TextStyle(
                    fontSize: 18,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w700,
                    color: Color(0xFF5D4037),
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),
                // 错误信息
                Text(
                  _errorMessage ?? '未知错误',
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF8B7355),
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 24),
                // 重试按钮
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _isLoading = true;
                      _errorMessage = null;
                      _countdownSeconds = 100;
                    });
                    _loadWalletInfo();
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 14),
                    decoration: BoxDecoration(
                      color: const Color(0xFFD4A84B),
                      borderRadius: BorderRadius.circular(12),
                      boxShadow: const [
                        BoxShadow(
                          color: Color(0x33D4A84B),
                          blurRadius: 8,
                          offset: Offset(0, 4),
                        ),
                      ],
                    ),
                    child: const Text(
                      '重新尝试',
                      style: TextStyle(
                        fontSize: 16,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w700,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建内容（带占位数据）
  Widget _buildContentWithPlaceholder() {
    // 使用占位数据或真实数据
    final displayWords = _mnemonicWords.isNotEmpty
        ? _mnemonicWords
        : List.generate(12, (i) => '******');
    final displayKava = _kavaAddress ?? '0x••••••••••••••••••••';
    final displayDst = _dstAddress ?? '0x••••••••••••••••••••';
    final displayBsc = _bscAddress ?? '0x••••••••••••••••••••';

    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        children: [
          const SizedBox(height: 8),
          // 助记词卡片 (使用占位或真实数据)
          _buildMnemonicCardWithData(displayWords),
          const SizedBox(height: 16),
          // 警告提示
          _buildWarningCard(),
          const SizedBox(height: 16),
          // 钱包地址卡片 (使用占位或真实数据)
          _buildAddressCardWithData(displayKava, displayDst, displayBsc),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildAppBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _goBack,
            child: Container(
              width: 44,
              height: 44,
              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: 44, height: 44),
        ],
      ),
    );
  }

  /// 构建助记词卡片
  Widget _buildMnemonicCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFFFFDF5),
        borderRadius: BorderRadius.circular(16),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0D000000),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和操作按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '您的助记词',
                style: TextStyle(
                  fontSize: 18,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w700,
                  height: 1.25,
                  letterSpacing: -0.27,
                  color: Color(0xFF5D4037),
                ),
              ),
              Row(
                children: [
                  // 显示/隐藏按钮
                  GestureDetector(
                    onTap: _toggleVisibility,
                    child: Container(
                      padding: const EdgeInsets.all(4),
                      child: Icon(
                        _isHidden ? Icons.visibility : Icons.visibility_off,
                        color: const Color(0xFF8B7355),
                        size: 22,
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  // 下载按钮
                  GestureDetector(
                    onTap: _isDownloading ? null : _downloadMnemonic,
                    child: Container(
                      padding: const EdgeInsets.all(4),
                      child: _isDownloading
                          ? const SizedBox(
                              width: 22,
                              height: 22,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  Color(0xFF8B7355),
                                ),
                              ),
                            )
                          : const Icon(
                              Icons.file_download_outlined,
                              color: Color(0xFF8B7355),
                              size: 22,
                            ),
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 20),
          // 助记词网格
          _buildMnemonicGrid(),
          const SizedBox(height: 20),
          // 复制全部按钮
          _buildCopyAllButton(),
        ],
      ),
    );
  }

  /// 构建助记词网格 (4行3列)
  Widget _buildMnemonicGrid() {
    return Column(
      children: [
        for (int row = 0; row < 4; row++)
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Row(
              children: [
                for (int col = 0; col < 3; col++)
                  Expanded(
                    child: _buildMnemonicWord(
                      row * 3 + col + 1,
                      _mnemonicWords.length > row * 3 + col
                          ? _mnemonicWords[row * 3 + col]
                          : '',
                    ),
                  ),
              ],
            ),
          ),
      ],
    );
  }

  /// 构建单个助记词项
  Widget _buildMnemonicWord(int index, String word) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 序号
        Text(
          '$index.',
          style: const TextStyle(
            fontSize: 14,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w500,
            height: 1.43,
            color: Color(0xCC8B7355),
          ),
        ),
        const SizedBox(width: 6),
        // 单词
        Text(
          _isHidden ? '******' : word,
          style: const TextStyle(
            fontSize: 15,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            height: 1.5,
            color: Color(0xFF5D4037),
          ),
        ),
      ],
    );
  }

  /// 构建复制全部按钮
  Widget _buildCopyAllButton() {
    return GestureDetector(
      onTap: _copyAllMnemonic,
      child: Container(
        width: double.infinity,
        height: 44,
        decoration: BoxDecoration(
          color: const Color(0xFFF5ECD9),
          borderRadius: BorderRadius.circular(10),
        ),
        child: const Center(
          child: Text(
            '复制全部',
            style: TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w600,
              height: 1.5,
              color: Color(0xFF8B7355),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建助记词卡片（带数据参数）
  Widget _buildMnemonicCardWithData(List<String> words) {
    final isPlaceholder = words.isNotEmpty && words[0] == '******';
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFFFFDF5),
        borderRadius: BorderRadius.circular(16),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0D000000),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和操作按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '您的助记词',
                style: TextStyle(
                  fontSize: 18,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w700,
                  height: 1.25,
                  letterSpacing: -0.27,
                  color: Color(0xFF5D4037),
                ),
              ),
              // 仅在非占位状态时显示操作按钮
              if (!isPlaceholder)
                Row(
                  children: [
                    // 显示/隐藏按钮
                    GestureDetector(
                      onTap: _toggleVisibility,
                      child: Container(
                        padding: const EdgeInsets.all(4),
                        child: Icon(
                          _isHidden ? Icons.visibility : Icons.visibility_off,
                          color: const Color(0xFF8B7355),
                          size: 22,
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    // 下载按钮
                    GestureDetector(
                      onTap: _isDownloading ? null : _downloadMnemonic,
                      child: Container(
                        padding: const EdgeInsets.all(4),
                        child: _isDownloading
                            ? const SizedBox(
                                width: 22,
                                height: 22,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                    Color(0xFF8B7355),
                                  ),
                                ),
                              )
                            : const Icon(
                                Icons.file_download_outlined,
                                color: Color(0xFF8B7355),
                                size: 22,
                              ),
                      ),
                    ),
                  ],
                ),
            ],
          ),
          const SizedBox(height: 20),
          // 助记词网格
          _buildMnemonicGridWithData(words),
          const SizedBox(height: 20),
          // 复制全部按钮（仅在非占位状态时可用）
          _buildCopyAllButtonWithState(!isPlaceholder),
        ],
      ),
    );
  }

  /// 构建助记词网格（带数据参数）
  Widget _buildMnemonicGridWithData(List<String> words) {
    return Column(
      children: [
        for (int row = 0; row < 4; row++)
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Row(
              children: [
                for (int col = 0; col < 3; col++)
                  Expanded(
                    child: _buildMnemonicWordWithData(
                      row * 3 + col + 1,
                      words.length > row * 3 + col ? words[row * 3 + col] : '',
                    ),
                  ),
              ],
            ),
          ),
      ],
    );
  }

  /// 构建单个助记词项（带数据参数）
  Widget _buildMnemonicWordWithData(int index, String word) {
    final isPlaceholder = word == '******';
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 序号
        Text(
          '$index.',
          style: TextStyle(
            fontSize: 14,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w500,
            height: 1.43,
            color: isPlaceholder
                ? const Color(0x668B7355)
                : const Color(0xCC8B7355),
          ),
        ),
        const SizedBox(width: 6),
        // 单词
        Text(
          _isHidden && !isPlaceholder ? '******' : word,
          style: TextStyle(
            fontSize: 15,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            height: 1.5,
            color: isPlaceholder
                ? const Color(0x665D4037)
                : const Color(0xFF5D4037),
          ),
        ),
      ],
    );
  }

  /// 构建复制全部按钮（带状态）
  Widget _buildCopyAllButtonWithState(bool enabled) {
    return GestureDetector(
      onTap: enabled ? _copyAllMnemonic : null,
      child: Container(
        width: double.infinity,
        height: 44,
        decoration: BoxDecoration(
          color: enabled
              ? const Color(0xFFF5ECD9)
              : const Color(0xFFE8E0D0),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Center(
          child: Text(
            '复制全部',
            style: TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w600,
              height: 1.5,
              color: enabled
                  ? const Color(0xFF8B7355)
                  : const Color(0x668B7355),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建钱包地址卡片（带数据参数）
  Widget _buildAddressCardWithData(String kava, String dst, String bsc) {
    final isPlaceholder = kava.contains('••••');
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: const Color(0xFFFFFDF5),
        borderRadius: BorderRadius.circular(16),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0D000000),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          _buildAddressItemWithData(
            iconWidget: _buildChainIcon(),
            label: 'KAVA 地址',
            address: kava,
            showBorder: true,
            isPlaceholder: isPlaceholder,
          ),
          _buildAddressItemWithData(
            iconWidget: _buildChainIcon(),
            label: 'DST 地址',
            address: dst,
            showBorder: true,
            isPlaceholder: isPlaceholder,
          ),
          _buildAddressItemWithData(
            iconWidget: _buildChainIcon(),
            label: 'BSC 地址',
            address: bsc,
            showBorder: true,
            isPlaceholder: isPlaceholder,
          ),
          _buildAddressItemWithData(
            iconWidget: _buildSequenceIcon(),
            label: '序列号',
            address: widget.userSerialNum,
            showBorder: false,
            isPlaceholder: false,
          ),
        ],
      ),
    );
  }

  /// 构建地址项（带占位状态）
  Widget _buildAddressItemWithData({
    required Widget iconWidget,
    required String label,
    required String address,
    required bool showBorder,
    required bool isPlaceholder,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      decoration: BoxDecoration(
        border: showBorder
            ? const Border(
                bottom: BorderSide(
                  color: Color(0x1A5D4037),
                  width: 1,
                ),
              )
            : null,
      ),
      child: Row(
        children: [
          // 图标
          iconWidget,
          const SizedBox(width: 14),
          // 标签和地址
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    height: 1.5,
                    color: isPlaceholder
                        ? const Color(0x995D4037)
                        : const Color(0xFF5D4037),
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  _formatAddress(address),
                  style: TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    height: 1.5,
                    color: isPlaceholder
                        ? const Color(0x66756452)
                        : const Color(0x99756452),
                  ),
                ),
              ],
            ),
          ),
          // 复制按钮（仅在非占位状态时可用）
          if (!isPlaceholder)
            GestureDetector(
              onTap: () => _copyAddress(address, label),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                child: const Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.copy_rounded,
                      color: Color(0xCC8B7355),
                      size: 16,
                    ),
                    SizedBox(width: 4),
                    Text(
                      '复制',
                      style: TextStyle(
                        fontSize: 14,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w500,
                        height: 1.5,
                        color: Color(0xCC8B7355),
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建警告卡片
  Widget _buildWarningCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF0E0),
        borderRadius: BorderRadius.circular(12),
      ),
      child: const Text(
        '请妥善保管您的助记词，丢失将无法恢复账号。',
        style: TextStyle(
          fontSize: 14,
          fontFamily: 'Inter',
          fontWeight: FontWeight.w500,
          height: 1.5,
          color: Color(0xFFCC6B2C),
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  /// 构建钱包地址卡片 (旧方法，保留向后兼容)
  Widget _buildAddressCard() {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: const Color(0xFFFFFDF5),
        borderRadius: BorderRadius.circular(16),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0D000000),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          if (_kavaAddress != null)
            _buildAddressItem(
              iconWidget: _buildChainIcon(),
              label: 'KAVA 地址',
              address: _kavaAddress!,
              showBorder: true,
            ),
          if (_dstAddress != null)
            _buildAddressItem(
              iconWidget: _buildChainIcon(),
              label: 'DST 地址',
              address: _dstAddress!,
              showBorder: true,
            ),
          if (_bscAddress != null)
            _buildAddressItem(
              iconWidget: _buildChainIcon(),
              label: 'BSC 地址',
              address: _bscAddress!,
              showBorder: true,
            ),
          _buildAddressItem(
            iconWidget: _buildSequenceIcon(),
            label: '序列号',
            address: widget.userSerialNum,
            showBorder: false,
          ),
        ],
      ),
    );
  }

  /// 构建链图标 (黄色背景圆角方形)
  Widget _buildChainIcon() {
    return Container(
      width: 44,
      height: 44,
      decoration: BoxDecoration(
        color: const Color(0xFFFFF3D6),
        borderRadius: BorderRadius.circular(10),
      ),
      child: const Center(
        child: Icon(
          Icons.credit_card,
          color: Color(0xFFD4A84B),
          size: 22,
        ),
      ),
    );
  }

  /// 构建序列号图标 (# 符号)
  Widget _buildSequenceIcon() {
    return Container(
      width: 44,
      height: 44,
      decoration: BoxDecoration(
        color: const Color(0xFFFFF3D6),
        borderRadius: BorderRadius.circular(10),
      ),
      child: const Center(
        child: Text(
          '#',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w700,
            color: Color(0xFFD4A84B),
          ),
        ),
      ),
    );
  }

  /// 构建地址项
  Widget _buildAddressItem({
    required Widget iconWidget,
    required String label,
    required String address,
    required bool showBorder,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      decoration: BoxDecoration(
        border: showBorder
            ? const Border(
                bottom: BorderSide(
                  color: Color(0x1A5D4037),
                  width: 1,
                ),
              )
            : null,
      ),
      child: Row(
        children: [
          // 图标
          iconWidget,
          const SizedBox(width: 14),
          // 标签和地址
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: const TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    height: 1.5,
                    color: Color(0xFF5D4037),
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  _formatAddress(address),
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    height: 1.5,
                    color: Color(0x99756452),
                  ),
                ),
              ],
            ),
          ),
          // 复制按钮
          GestureDetector(
            onTap: () => _copyAddress(address, label),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
              child: const Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.copy_rounded,
                    color: Color(0xCC8B7355),
                    size: 16,
                  ),
                  SizedBox(width: 4),
                  Text(
                    '复制',
                    style: TextStyle(
                      fontSize: 14,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w500,
                      height: 1.5,
                      color: Color(0xCC8B7355),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 格式化地址显示 (显示前6位和后4位)
  String _formatAddress(String address) {
    if (address.length <= 10) return address;
    return '${address.substring(0, 6)}...${address.substring(address.length - 4)}';
  }

  /// 构建底部按钮区域
  Widget _buildBottomButtons() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
      decoration: const BoxDecoration(
        color: Color(0xFFFFE4B5),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 我已备份助记词按钮
          GestureDetector(
            onTap: _confirmBackup,
            child: Container(
              width: double.infinity,
              height: 52,
              decoration: BoxDecoration(
                color: const Color(0xFFD4A84B),
                borderRadius: BorderRadius.circular(12),
                boxShadow: const [
                  BoxShadow(
                    color: Color(0x33D4A84B),
                    blurRadius: 8,
                    offset: Offset(0, 4),
                  ),
                ],
              ),
              child: const Center(
                child: Text(
                  '我已备份助记词',
                  style: TextStyle(
                    fontSize: 17,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w700,
                    height: 1.5,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(height: 14),
          // 返回上一步
          GestureDetector(
            onTap: _goBack,
            child: const Text(
              '返回上一步',
              style: TextStyle(
                fontSize: 15,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.5,
                color: Color(0xFF8B7355),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
