import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/account_service.dart';
import '../../../../core/services/multi_account_service.dart';
import '../../../../routes/route_paths.dart';
import 'set_password_page.dart';

/// 短信验证码页面
/// 输入6位验证码完成注册/登录
class SmsVerifyPage extends ConsumerStatefulWidget {
  final String phoneNumber;
  final SmsCodeType type;
  final String? inviterReferralCode;

  const SmsVerifyPage({
    super.key,
    required this.phoneNumber,
    required this.type,
    this.inviterReferralCode,
  });

  @override
  ConsumerState<SmsVerifyPage> createState() => _SmsVerifyPageState();
}

class _SmsVerifyPageState extends ConsumerState<SmsVerifyPage> {
  final List<TextEditingController> _controllers = List.generate(
    6,
    (_) => TextEditingController(),
  );
  final List<FocusNode> _focusNodes = List.generate(6, (_) => FocusNode());

  bool _isVerifying = false;
  String? _errorMessage;

  // 倒计时
  int _countdown = 60;
  Timer? _countdownTimer;
  bool _canResend = false;

  // 跳过验证倒计时（3分钟后显示跳过按钮）
  int _skipCountdown = 180;
  Timer? _skipTimer;
  bool _canSkipVerify = false;

  @override
  void initState() {
    super.initState();
    debugPrint('[SmsVerifyPage] initState - phoneNumber: ${_maskPhoneNumber(widget.phoneNumber)}, type: ${widget.type}');
    _startCountdown();
    // 只在注册模式下启动跳过验证倒计时
    if (widget.type == SmsCodeType.register) {
      _startSkipCountdown();
    }
    // 自动聚焦第一个输入框
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _focusNodes[0].requestFocus();
    });
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _skipTimer?.cancel();
    for (final controller in _controllers) {
      controller.dispose();
    }
    for (final focusNode in _focusNodes) {
      focusNode.dispose();
    }
    super.dispose();
  }

  void _startCountdown() {
    _countdown = 60;
    _canResend = false;
    _countdownTimer?.cancel();
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 0) {
        setState(() {
          _countdown--;
        });
      } else {
        setState(() {
          _canResend = true;
        });
        timer.cancel();
      }
    });
  }

  /// 启动跳过验证倒计时（3分钟）
  void _startSkipCountdown() {
    _skipCountdown = 180;
    _canSkipVerify = false;
    _skipTimer?.cancel();
    _skipTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_skipCountdown > 0) {
        setState(() {
          _skipCountdown--;
        });
      } else {
        setState(() {
          _canSkipVerify = true;
        });
        timer.cancel();
      }
    });
  }

  /// 跳过验证，继续注册
  void _skipVerification() {
    debugPrint('[SmsVerifyPage] 用户选择跳过验证，跳转到设置密码页面');
    context.go(
      RoutePaths.setPassword,
      extra: SetPasswordParams(
        phoneNumber: widget.phoneNumber,
        smsCode: null, // 跳过验证时没有验证码
        inviterReferralCode: widget.inviterReferralCode,
        skipVerify: true, // 标记跳过验证
      ),
    );
  }

  String _getVerificationCode() {
    return _controllers.map((c) => c.text).join();
  }

  /// 重新发送验证码
  Future<void> _resendCode() async {
    if (!_canResend) return;

    try {
      final accountService = ref.read(accountServiceProvider);
      await accountService.sendSmsCode(widget.phoneNumber, widget.type);

      if (mounted) {
        _startCountdown();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '验证码已发送',
              style: TextStyle(fontSize: 14.sp),
            ),
            backgroundColor: const Color(0xFF2E7D32),
            behavior: SnackBarBehavior.floating,
            margin: EdgeInsets.all(16.w),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8.r),
            ),
          ),
        );
      }
    } catch (e) {
      debugPrint('[SmsVerifyPage] 重新发送验证码失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '发送失败: ${e.toString().replaceAll('Exception: ', '')}',
              style: TextStyle(fontSize: 14.sp),
            ),
            backgroundColor: Colors.red,
            behavior: SnackBarBehavior.floating,
            margin: EdgeInsets.all(16.w),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8.r),
            ),
          ),
        );
      }
    }
  }

  /// 验证验证码
  Future<void> _verifyCode() async {
    final code = _getVerificationCode();
    if (code.length != 6) {
      setState(() {
        _errorMessage = '请输入完整的验证码';
      });
      return;
    }

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

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

      if (widget.type == SmsCodeType.register) {
        // 注册流程：直接跳转到设置密码页面，由密码页面一起调用 register-by-phone API
        debugPrint('[SmsVerifyPage] 验证码输入完成，跳转到设置密码页面');

        if (!mounted) return;

        // 跳转到设置密码页面，传递手机号和验证码
        context.go(
          RoutePaths.setPassword,
          extra: SetPasswordParams(
            phoneNumber: widget.phoneNumber,
            smsCode: code,
            inviterReferralCode: widget.inviterReferralCode,
          ),
        );
        return; // 提前返回，不需要等待
      } else if (widget.type == SmsCodeType.login) {
        // 登录
        debugPrint('[SmsVerifyPage] 开始登录...');
        final response = await accountService.loginByPhone(
          phoneNumber: widget.phoneNumber,
          smsCode: code,
        );
        debugPrint('[SmsVerifyPage] 登录成功: ${response.accountSequence}');

        if (!mounted) return;

        // 获取用户资料并添加到多账号列表
        try {
          final profile = await accountService.getMyProfile();
          final multiAccountService = ref.read(multiAccountServiceProvider);

          await multiAccountService.addAccount(
            AccountSummary(
              userSerialNum: response.accountSequence,
              username: profile['nickname'] as String? ?? '用户${response.accountSequence}',
              avatarSvg: profile['avatarSvg'] as String?,
              avatarUrl: profile['avatarUrl'] as String?,
              createdAt: DateTime.now(),
            ),
          );
          await multiAccountService.setCurrentAccountId(response.accountSequence);
          debugPrint('[SmsVerifyPage] 已添加到多账号列表');
        } catch (e) {
          debugPrint('[SmsVerifyPage] 获取用户资料失败，使用默认信息: $e');
          // 即使获取资料失败，也添加到账号列表（使用默认信息）
          final multiAccountService = ref.read(multiAccountServiceProvider);
          await multiAccountService.addAccount(
            AccountSummary(
              userSerialNum: response.accountSequence,
              username: '用户${response.accountSequence}',
              createdAt: DateTime.now(),
            ),
          );
          await multiAccountService.setCurrentAccountId(response.accountSequence);
        }

        if (!mounted) return;

        // 跳转到主页
        context.go(RoutePaths.mining);
      }
    } catch (e) {
      debugPrint('[SmsVerifyPage] 验证失败: $e');
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
        // 清空验证码
        for (final controller in _controllers) {
          controller.clear();
        }
        _focusNodes[0].requestFocus();
      }
    } finally {
      if (mounted) {
        setState(() {
          _isVerifying = false;
        });
      }
    }
  }

  void _onCodeChanged(int index, String value) {
    // 清除错误信息
    if (_errorMessage != null) {
      setState(() {
        _errorMessage = null;
      });
    }

    if (value.isNotEmpty) {
      // 输入了字符，移动到下一个
      if (index < 5) {
        _focusNodes[index + 1].requestFocus();
      } else {
        // 输入完成，验证
        _focusNodes[index].unfocus();
        _verifyCode();
      }
    }
  }

  void _onKeyEvent(int index, KeyEvent event) {
    if (event is KeyDownEvent) {
      if (event.logicalKey == LogicalKeyboardKey.backspace) {
        if (_controllers[index].text.isEmpty && index > 0) {
          // 当前格为空，删除前一格
          _controllers[index - 1].clear();
          _focusNodes[index - 1].requestFocus();
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF333333)),
          onPressed: () => context.pop(),
        ),
        title: Text(
          widget.type == SmsCodeType.register ? '手机号注册' : '手机号登录',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: const Color(0xFF333333),
          ),
        ),
        centerTitle: true,
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 32.h),
                // 标题
                Text(
                  '输入验证码',
                  style: TextStyle(
                    fontSize: 24.sp,
                    fontWeight: FontWeight.w700,
                    color: const Color(0xFF333333),
                  ),
                ),
                SizedBox(height: 8.h),
                Text(
                  '验证码已发送至 ${_formatPhoneNumber(widget.phoneNumber)}',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFF999999),
                  ),
                ),
                SizedBox(height: 32.h),
                // 验证码输入框
                _buildCodeInputs(),
                // 错误信息
                if (_errorMessage != null) ...[
                  SizedBox(height: 16.h),
                  Text(
                    _errorMessage!,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.red,
                    ),
                  ),
                ],
                SizedBox(height: 24.h),
                // 重新发送按钮
                _buildResendButton(),
                // 跳过验证按钮（仅注册模式，2分钟后显示）
                if (widget.type == SmsCodeType.register) ...[
                  SizedBox(height: 16.h),
                  _buildSkipButton(),
                ],
                const Spacer(),
                // 验证中提示
                if (_isVerifying)
                  Center(
                    child: Column(
                      children: [
                        SizedBox(
                          width: 32.sp,
                          height: 32.sp,
                          child: const CircularProgressIndicator(
                            strokeWidth: 3,
                            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF2E7D32)),
                          ),
                        ),
                        SizedBox(height: 12.h),
                        Text(
                          widget.type == SmsCodeType.register ? '正在注册...' : '正在登录...',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: const Color(0xFF666666),
                          ),
                        ),
                      ],
                    ),
                  ),
                SizedBox(height: 32.h),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCodeInputs() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: List.generate(6, (index) {
        return SizedBox(
          width: 50.w,
          height: 60.h,
          child: KeyboardListener(
            focusNode: FocusNode(),
            onKeyEvent: (event) => _onKeyEvent(index, event),
            child: TextField(
              controller: _controllers[index],
              focusNode: _focusNodes[index],
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              maxLength: 1,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
              ],
              decoration: InputDecoration(
                counterText: '',
                filled: true,
                fillColor: const Color(0xFFF5F5F5),
                contentPadding: EdgeInsets.zero,  // 移除内边距，让数字完整居中显示
                isDense: true,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12.r),
                  borderSide: BorderSide.none,
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12.r),
                  borderSide: const BorderSide(
                    color: Color(0xFF2E7D32),
                    width: 2,
                  ),
                ),
                errorBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12.r),
                  borderSide: const BorderSide(
                    color: Colors.red,
                    width: 1,
                  ),
                ),
              ),
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.w700,
                color: const Color(0xFF333333),
              ),
              onChanged: (value) => _onCodeChanged(index, value),
            ),
          ),
        );
      }),
    );
  }

  Widget _buildResendButton() {
    return Center(
      child: GestureDetector(
        onTap: _canResend ? _resendCode : null,
        child: Text(
          _canResend ? '重新发送验证码' : '$_countdown秒后重新发送',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: _canResend
                ? const Color(0xFF2E7D32)
                : const Color(0xFF999999),
          ),
        ),
      ),
    );
  }

  /// 构建跳过验证按钮
  Widget _buildSkipButton() {
    if (_canSkipVerify) {
      // 2分钟后显示跳过按钮
      return Center(
        child: GestureDetector(
          onTap: _skipVerification,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
            decoration: BoxDecoration(
              color: const Color(0xFFFFF3E0),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  Icons.warning_amber_rounded,
                  size: 16.sp,
                  color: const Color(0xFFE65100),
                ),
                SizedBox(width: 6.w),
                Text(
                  '收不到验证码？跳过验证，稍后完成',
                  style: TextStyle(
                    fontSize: 13.sp,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xFFE65100),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    } else {
      // 2分钟内显示倒计时提示
      final minutes = _skipCountdown ~/ 60;
      final seconds = _skipCountdown % 60;
      return Center(
        child: Text(
          '收不到验证码？${minutes > 0 ? '${minutes}分' : ''}${seconds}秒后可跳过',
          style: TextStyle(
            fontSize: 12.sp,
            color: const Color(0xFFBDBDBD),
          ),
        ),
      );
    }
  }

  String _formatPhoneNumber(String phone) {
    if (phone.length != 11) return phone;
    // 显示完整手机号，用空格分隔便于阅读
    return '${phone.substring(0, 3)} ${phone.substring(3, 7)} ${phone.substring(7)}';
  }

  String _maskPhoneNumber(String phone) {
    if (phone.length < 7) return phone;
    return '${phone.substring(0, 3)}****${phone.substring(phone.length - 4)}';
  }
}
