import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../../routes/route_paths.dart';
import '../../../../routes/app_router.dart';
import '../../../../core/di/injection_container.dart';

/// 确认备份页面 - 验证用户是否正确备份了助记词
/// 用户需要勾选确认或选择正确的助记词单词才能完成验证
class VerifyMnemonicPage extends ConsumerStatefulWidget {
  /// 用户的助记词列表
  final List<String> mnemonicWords;
  /// KAVA 钱包地址
  final String kavaAddress;
  /// DST 钱包地址
  final String dstAddress;
  /// BSC 钱包地址
  final String bscAddress;
  /// 用户序列号
  final String userSerialNum;
  /// 推荐码
  final String? referralCode;

  const VerifyMnemonicPage({
    super.key,
    required this.mnemonicWords,
    required this.kavaAddress,
    required this.dstAddress,
    required this.bscAddress,
    required this.userSerialNum,
    this.referralCode,
  });

  @override
  ConsumerState<VerifyMnemonicPage> createState() => _VerifyMnemonicPageState();
}

class _VerifyMnemonicPageState extends ConsumerState<VerifyMnemonicPage> {
  // 勾选"我已备份助记词并理解风险"
  bool _isChecked = false;
  // 需要验证的单词索引 (随机生成，1-12)
  late int _verifyWordIndex;
  // 选项列表
  late List<String> _wordOptions;
  // 用户选择的单词
  String? _selectedWord;
  // 正确的单词
  late String _correctWord;
  // 是否正在创建账号
  bool _isCreating = false;

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

  /// 初始化验证数据
  void _initializeVerification() {
    final random = Random();
    // 随机选择一个位置 (1-12)
    _verifyWordIndex = random.nextInt(12) + 1;
    // 获取正确答案
    _correctWord = widget.mnemonicWords[_verifyWordIndex - 1];

    // 生成选项列表（包含正确答案和干扰项）
    _wordOptions = _generateOptions();
  }

  /// 生成选项列表
  List<String> _generateOptions() {
    final random = Random();
    final options = <String>[_correctWord];

    // 一些常见的 BIP39 单词作为干扰项
    final decoyWords = [
      'apple', 'banana', 'cherry', 'date', 'elder', 'fig', 'grape', 'honey',
      'kiwi', 'lemon', 'mango', 'nectar', 'orange', 'peach', 'queen', 'rose',
      'sugar', 'tiger', 'uncle', 'virus', 'water', 'yellow', 'zebra', 'zoo',
      'jungle', 'victory', 'wizard', 'anchor', 'brain', 'cloud',
    ];

    // 移除已存在于助记词中的单词
    final availableDecoys = decoyWords
        .where((word) => !widget.mnemonicWords.contains(word) && word != _correctWord)
        .toList();

    // 随机选择5个干扰项
    availableDecoys.shuffle(random);
    options.addAll(availableDecoys.take(5));

    // 打乱选项顺序
    options.shuffle(random);

    return options;
  }

  /// 选择单词
  void _selectWord(String word) {
    setState(() {
      _selectedWord = word;
    });
  }

  /// 检查是否可以提交
  bool get _canSubmit {
    // 方式1：勾选确认 → 直接通过
    // 方式2：不勾选 → 必须选择正确的单词
    if (_isChecked) {
      return true;
    }
    return _selectedWord == _correctWord;
  }

  /// 确认并创建账号
  Future<void> _confirmAndCreate() async {
    // 未勾选时，检查是否选择了单词
    if (!_isChecked && _selectedWord == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请勾选确认或选择正确的助记词单词'),
          backgroundColor: Color(0xFF8B5A2B),
        ),
      );
      return;
    }

    // 未勾选时，检查选择的单词是否正确
    if (!_isChecked && _selectedWord != _correctWord) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('选择的单词不正确，请重试'),
          backgroundColor: Color(0xFF991B1B),
        ),
      );
      return;
    }

    setState(() => _isCreating = true);

    try {
      // 使用 AccountService 标记助记词已备份
      final accountService = ref.read(accountServiceProvider);
      await accountService.markMnemonicBackedUp();

      if (!mounted) return;

      // 跳转到创建成功页面
      context.go(
        RoutePaths.walletCreated,
        extra: WalletCreatedParams(
          kavaAddress: widget.kavaAddress,
          dstAddress: widget.dstAddress,
          bscAddress: widget.bscAddress,
          userSerialNum: widget.userSerialNum,
          referralCode: widget.referralCode,
        ),
      );
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败: $e'),
          backgroundColor: const Color(0xFF991B1B),
        ),
      );
    } finally {
      if (mounted) {
        setState(() => _isCreating = false);
      }
    }
  }

  /// 返回查看助记词
  void _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(0xFFFFF8F0), // 更浅的米色顶部
              Color(0xFFFFE4B5), // 金黄色底部
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),
              // 内容区域
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(height: 24),
                      // 说明文字
                      _buildDescription(),
                      const SizedBox(height: 32),
                      // 勾选确认
                      _buildCheckbox(),
                      const SizedBox(height: 28),
                      // 分隔线
                      _buildDivider(),
                      const SizedBox(height: 28),
                      // 选择单词验证
                      _buildWordSelection(),
                    ],
                  ),
                ),
              ),
              // 底部按钮区域
              _buildBottomButtons(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  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 _buildDescription() {
    return const Text(
      '为保证助记词已被您正确保存，请通过以下方式确认：',
      style: TextStyle(
        fontSize: 16,
        fontFamily: 'Inter',
        height: 1.5,
        color: Color(0xFF5D4037),
      ),
    );
  }

  /// 构建勾选确认
  Widget _buildCheckbox() {
    return GestureDetector(
      onTap: () {
        setState(() {
          _isChecked = !_isChecked;
        });
      },
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 勾选框 - 金黄色圆角方形
          Container(
            width: 22,
            height: 22,
            decoration: BoxDecoration(
              color: _isChecked ? const Color(0xFFD4A84B) : const Color(0xFFFFF5E6),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(
                color: _isChecked ? const Color(0xFFD4A84B) : const Color(0xFFD4A84B),
                width: 1.5,
              ),
            ),
            child: _isChecked
                ? const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: 16,
                  )
                : null,
          ),
          const SizedBox(width: 12),
          const Text(
            '我已备份助记词并理解风险',
            style: TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w500,
              height: 1.5,
              color: Color(0xFF5D4037),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建分隔线
  Widget _buildDivider() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 1,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  const Color(0xFFD4A84B).withValues(alpha: 0.1),
                  const Color(0xFFD4A84B).withValues(alpha: 0.4),
                ],
              ),
            ),
          ),
        ),
        const Padding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          child: Text(
            '或',
            style: TextStyle(
              fontSize: 14,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w500,
              height: 1.43,
              color: Color(0xFF8B7355),
            ),
          ),
        ),
        Expanded(
          child: Container(
            height: 1,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  const Color(0xFFD4A84B).withValues(alpha: 0.4),
                  const Color(0xFFD4A84B).withValues(alpha: 0.1),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建单词选择验证
  Widget _buildWordSelection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '请选择你助记词中的第 $_verifyWordIndex 个单词',
          style: const TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w500,
            height: 1.5,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 20),
        // 选项按钮 - 使用网格布局
        Wrap(
          spacing: 10,
          runSpacing: 12,
          children: _wordOptions.map((word) => _buildWordOption(word)).toList(),
        ),
      ],
    );
  }

  /// 构建单词选项按钮
  Widget _buildWordOption(String word) {
    final isSelected = _selectedWord == word;

    return GestureDetector(
      onTap: () => _selectWord(word),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
        decoration: BoxDecoration(
          // 选中时使用浅金色背景，未选中时使用米色背景
          color: isSelected
              ? const Color(0xFFFFF5E6)
              : const Color(0xFFF5ECD9),
          borderRadius: BorderRadius.circular(10),
          border: isSelected
              ? Border.all(color: const Color(0xFFD4A84B), width: 1.5)
              : Border.all(color: Colors.transparent, width: 1.5),
        ),
        child: Text(
          word,
          style: TextStyle(
            fontSize: 15,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            height: 1.4,
            color: isSelected ? const Color(0xFFD4A84B) : const Color(0xFF5D4037),
          ),
        ),
      ),
    );
  }

  /// 构建底部按钮区域
  Widget _buildBottomButtons() {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
      decoration: const BoxDecoration(
        color: Color(0xFFFFE4B5),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 确认并创建账号按钮
          GestureDetector(
            onTap: _isCreating ? null : _confirmAndCreate,
            child: Container(
              width: double.infinity,
              height: 52,
              decoration: BoxDecoration(
                // 禁用状态使用浅灰棕色，启用状态使用金色
                color: _canSubmit
                    ? const Color(0xFFD4A84B)
                    : const Color(0xFFCBBDA8),
                borderRadius: BorderRadius.circular(12),
                boxShadow: _canSubmit
                    ? const [
                        BoxShadow(
                          color: Color(0x33D4A84B),
                          blurRadius: 8,
                          offset: Offset(0, 4),
                        ),
                      ]
                    : null,
              ),
              child: Center(
                child: _isCreating
                    ? const SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : Text(
                        '确认并创建账号',
                        style: TextStyle(
                          fontSize: 17,
                          fontFamily: 'Inter',
                          fontWeight: FontWeight.w700,
                          height: 1.5,
                          color: _canSubmit
                              ? Colors.white
                              : const Color(0xB3FFFFFF),
                        ),
                      ),
              ),
            ),
          ),
          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),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
