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 '../../../../core/di/injection_container.dart';
import '../../../../core/services/multi_account_service.dart';
import '../../../../routes/route_paths.dart';

/// 导入助记词页面 - 用于恢复已有账户
/// 用户输入序列号和12个助记词来恢复钱包
class ImportMnemonicPage extends ConsumerStatefulWidget {
  const ImportMnemonicPage({super.key});

  @override
  ConsumerState<ImportMnemonicPage> createState() => _ImportMnemonicPageState();
}

class _ImportMnemonicPageState extends ConsumerState<ImportMnemonicPage> {
  // 序列号输入控制器
  final TextEditingController _serialNumController = TextEditingController();

  // 12个助记词输入控制器
  final List<TextEditingController> _controllers = List.generate(
    12,
    (_) => TextEditingController(),
  );

  // 12个焦点节点
  final List<FocusNode> _focusNodes = List.generate(
    12,
    (_) => FocusNode(),
  );

  // 是否正在提交
  bool _isSubmitting = false;

  // 错误信息
  String? _errorMessage;

  @override
  void dispose() {
    _serialNumController.dispose();
    for (final controller in _controllers) {
      controller.dispose();
    }
    for (final node in _focusNodes) {
      node.dispose();
    }
    super.dispose();
  }

  /// 获取完整的助记词字符串
  String get _mnemonic {
    return _controllers
        .map((c) => c.text.trim().toLowerCase())
        .join(' ');
  }

  /// 获取序列号
  String? get _serialNum {
    final text = _serialNumController.text.trim();
    if (text.isEmpty) return null;
    return text;
  }

  /// 检查是否所有单词都已填写
  bool get _isComplete {
    final hasSerialNum = _serialNumController.text.trim().isNotEmpty;
    final hasAllWords = _controllers.every((c) => c.text.trim().isNotEmpty);
    return hasSerialNum && hasAllWords;
  }

  /// 导入并恢复账号
  Future<void> _importAndRecover() async {
    // 验证序列号
    final serialNum = _serialNum;
    if (serialNum == null) {
      setState(() {
        _errorMessage = '请输入有效的序列号';
      });
      return;
    }

    // 验证助记词
    if (!_controllers.every((c) => c.text.trim().isNotEmpty)) {
      setState(() {
        _errorMessage = '请填写完整的12个助记词';
      });
      return;
    }

    setState(() {
      _isSubmitting = true;
      _errorMessage = null;
    });

    try {
      final accountService = ref.read(accountServiceProvider);

      // 调用恢复账户API
      final response = await accountService.recoverByMnemonic(
        serialNum,
        _mnemonic,
      );

      if (!mounted) return;

      // 将账号添加到多账号列表
      final multiAccountService = ref.read(multiAccountServiceProvider);
      await multiAccountService.addAccount(
        AccountSummary(
          userSerialNum: response.userSerialNum,
          username: response.username,
          avatarSvg: response.avatarSvg,
          createdAt: DateTime.now(),
        ),
      );
      await multiAccountService.setCurrentAccountId(response.userSerialNum);
      debugPrint('[ImportMnemonicPage] 已添加到多账号列表');

      if (!mounted) return;

      // 恢复成功，跳转到主页
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('账户恢复成功！序列号: ${response.userSerialNum}'),
          backgroundColor: const Color(0xFF52C41A),
        ),
      );

      // 跳转到主页
      context.go(RoutePaths.ranking);
    } catch (e) {
      debugPrint('恢复账户失败: $e');
      if (!mounted) return;

      setState(() {
        _errorMessage = e.toString().replaceAll('Exception: ', '');
      });
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  /// 返回创建账号页面
  void _goBack() {
    context.pop();
  }

  /// 处理单词输入完成，自动跳转到下一个
  void _onWordChanged(int index, String value) {
    // 清除错误信息
    if (_errorMessage != null) {
      setState(() {
        _errorMessage = null;
      });
    }

    // 如果输入了空格，可能是粘贴了多个单词
    if (value.contains(' ')) {
      _handlePaste(index, value);
      return;
    }

    // 刷新状态以更新按钮
    setState(() {});
  }

  /// 处理粘贴多个单词的情况
  void _handlePaste(int startIndex, String value) {
    final words = value.trim().split(RegExp(r'\s+'));

    for (int i = 0; i < words.length && startIndex + i < 12; i++) {
      _controllers[startIndex + i].text = words[i].toLowerCase();
    }

    // 焦点移动到最后一个填写的位置或下一个空位
    final nextIndex = (startIndex + words.length).clamp(0, 11);
    _focusNodes[nextIndex].requestFocus();

    setState(() {});
  }

  @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: SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 16),
                        // 序列号输入
                        _buildSerialNumInput(),
                        const SizedBox(height: 16),
                        // 助记词标签
                        const Text(
                          '助记词',
                          style: TextStyle(
                            fontSize: 14,
                            fontFamily: 'Inter',
                            fontWeight: FontWeight.w500,
                            color: Color(0xFF745D43),
                          ),
                        ),
                        const SizedBox(height: 8),
                        // 助记词输入区域
                        _buildMnemonicInputArea(),
                        const SizedBox(height: 12),
                        // 提示文字
                        const Text(
                          '支持 KAVA / DST / BSC 链的钱包导入。请在私密环境中操作。',
                          style: TextStyle(
                            fontSize: 14,
                            fontFamily: 'Inter',
                            height: 1.5,
                            color: Color(0xFF745D43),
                          ),
                        ),
                        // 错误信息
                        if (_errorMessage != null) ...[
                          const SizedBox(height: 12),
                          Container(
                            width: double.infinity,
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color: const Color(0xFFFFE4E4),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              _errorMessage!,
                              style: const TextStyle(
                                fontSize: 14,
                                color: Color(0xFFD32F2F),
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
              ),
              // 底部按钮区域
              _buildFooter(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildAppBar() {
    return Container(
      height: 56,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 返回按钮
          Positioned(
            left: 0,
            child: GestureDetector(
              onTap: _goBack,
              child: Container(
                width: 48,
                height: 48,
                alignment: Alignment.centerLeft,
                child: const Icon(
                  Icons.arrow_back_ios,
                  color: Color(0xFF5D4037),
                  size: 20,
                ),
              ),
            ),
          ),
          // 标题
          const Text(
            '导入助记词',
            style: TextStyle(
              fontSize: 18,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w700,
              letterSpacing: -0.27,
              color: Color(0xFF5D4037),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建序列号输入框
  Widget _buildSerialNumInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '序列号',
          style: TextStyle(
            fontSize: 14,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w500,
            color: Color(0xFF745D43),
          ),
        ),
        const SizedBox(height: 8),
        Container(
          height: 48,
          decoration: BoxDecoration(
            color: const Color(0xFFFFFDF8),
            borderRadius: BorderRadius.circular(8),
            border: Border.all(
              color: const Color(0x338B5A2B),
              width: 1,
            ),
          ),
          child: TextField(
            controller: _serialNumController,
            style: const TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              color: Color(0xFF5D4037),
            ),
            cursorColor: const Color(0xFF8B5A2B),
            decoration: const InputDecoration(
              border: InputBorder.none,
              enabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none,
              errorBorder: InputBorder.none,
              disabledBorder: InputBorder.none,
              contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              filled: false,
              hintText: '请输入账户序列号（如 D2512110008）',
              hintStyle: TextStyle(
                fontSize: 16,
                color: Color(0x668B5A2B),
              ),
            ),
            keyboardType: TextInputType.text,
            onChanged: (_) {
              if (_errorMessage != null) {
                setState(() {
                  _errorMessage = null;
                });
              }
              setState(() {});
            },
          ),
        ),
      ],
    );
  }

  /// 构建助记词输入区域
  Widget _buildMnemonicInputArea() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFFFFDF8),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0x338B5A2B),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          // 4行，每行3个单词
          for (int row = 0; row < 4; row++) ...[
            if (row > 0) const SizedBox(height: 12),
            Row(
              children: [
                for (int col = 0; col < 3; col++) ...[
                  if (col > 0) const SizedBox(width: 12),
                  Expanded(
                    child: _buildWordInput(row * 3 + col),
                  ),
                ],
              ],
            ),
          ],
        ],
      ),
    );
  }

  /// 构建单个单词输入框
  Widget _buildWordInput(int index) {
    return Container(
      height: 44,
      decoration: BoxDecoration(
        color: const Color(0xFFFFF7E6),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: const Color(0x338B5A2B),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          // 序号
          Container(
            width: 28,
            alignment: Alignment.center,
            child: Text(
              '${index + 1}',
              style: const TextStyle(
                fontSize: 12,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                color: Color(0xFF8B5A2B),
              ),
            ),
          ),
          // 输入框 - 完全透明，只保留功能
          Expanded(
            child: TextField(
              controller: _controllers[index],
              focusNode: _focusNodes[index],
              style: const TextStyle(
                fontSize: 14,
                fontFamily: 'Inter',
                color: Color(0xFF5D4037),
              ),
              cursorColor: const Color(0xFF8B5A2B),
              decoration: const InputDecoration(
                border: InputBorder.none,
                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(horizontal: 4, vertical: 10),
                isDense: true,
                filled: false,
              ),
              textInputAction: index < 11 ? TextInputAction.next : TextInputAction.done,
              autocorrect: false,
              enableSuggestions: false,
              onChanged: (value) => _onWordChanged(index, value),
              onSubmitted: (_) {
                if (index < 11) {
                  _focusNodes[index + 1].requestFocus();
                } else {
                  // 最后一个，尝试提交
                  if (_isComplete) {
                    _importAndRecover();
                  }
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建底部按钮区域
  Widget _buildFooter() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
      child: Column(
        children: [
          // 导入并恢复账号按钮
          GestureDetector(
            onTap: _isSubmitting ? null : _importAndRecover,
            child: Opacity(
              opacity: _isComplete && !_isSubmitting ? 1.0 : 0.5,
              child: Container(
                width: double.infinity,
                height: 48,
                decoration: BoxDecoration(
                  color: const Color(0xFF8B5A2B),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Center(
                  child: _isSubmitting
                      ? const SizedBox(
                          width: 24,
                          height: 24,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                          ),
                        )
                      : const Text(
                          '导入并恢复账号',
                          style: TextStyle(
                            fontSize: 16,
                            fontFamily: 'Inter',
                            fontWeight: FontWeight.w700,
                            letterSpacing: 0.24,
                            color: Color(0xB3FFFFFF),
                          ),
                        ),
                ),
              ),
            ),
          ),
          const SizedBox(height: 12),
          // 返回创建账号链接
          GestureDetector(
            onTap: _goBack,
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 8),
              child: const Text(
                '返回创建账号',
                style: TextStyle(
                  fontSize: 14,
                  fontFamily: 'Inter',
                  decoration: TextDecoration.underline,
                  color: Color(0xFF745D43),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
