import 'package:flutter/material.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/multi_account_service.dart';
import '../../../../routes/route_paths.dart';
import '../providers/auth_provider.dart';

/// 设置登录密码页面参数
class SetPasswordParams {
  final String? userSerialNum; // 如果有则表示已创建账号(旧流程)，无则表示需要创建账号(新流程)
  final String? inviterReferralCode;
  final String? phoneNumber; // 新流程需要
  final String? smsCode; // 新流程需要（跳过验证时为 null）
  final bool skipVerify; // 是否跳过短信验证

  SetPasswordParams({
    this.userSerialNum,
    this.inviterReferralCode,
    this.phoneNumber,
    this.smsCode,
    this.skipVerify = false,
  });
}

/// 设置登录密码页面
/// 用户完成短信验证后，设置登录密码
class SetPasswordPage extends ConsumerStatefulWidget {
  final String? userSerialNum; // 旧流程：已创建账号
  final String? inviterReferralCode;
  final String? phoneNumber; // 新流程：手机号
  final String? smsCode; // 新流程：验证码（跳过验证时为 null）
  final bool skipVerify; // 是否跳过短信验证

  const SetPasswordPage({
    super.key,
    this.userSerialNum,
    this.inviterReferralCode,
    this.phoneNumber,
    this.smsCode,
    this.skipVerify = false,
  });

  @override
  ConsumerState<SetPasswordPage> createState() => _SetPasswordPageState();
}

class _SetPasswordPageState extends ConsumerState<SetPasswordPage> {
  final _formKey = GlobalKey<FormState>();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();

  bool _isPasswordVisible = false;
  bool _isConfirmPasswordVisible = false;
  bool _isSubmitting = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    debugPrint('[SetPasswordPage] initState - userSerialNum: ${widget.userSerialNum}, phoneNumber: ${widget.phoneNumber != null ? "***" : "null"}');
  }

  @override
  void dispose() {
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  /// 验证密码强度
  String? _validatePassword(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入密码';
    }
    if (value.length < 6) {
      return '密码长度至少6位';
    }
    if (value.length > 20) {
      return '密码长度不能超过20位';
    }
    // 检查是否包含字母和数字
    if (!RegExp(r'^(?=.*[A-Za-z])(?=.*\d).+$').hasMatch(value)) {
      return '密码需包含字母和数字';
    }
    return null;
  }

  /// 验证确认密码
  String? _validateConfirmPassword(String? value) {
    if (value == null || value.isEmpty) {
      return '请再次输入密码';
    }
    if (value != _passwordController.text) {
      return '两次输入的密码不一致';
    }
    return null;
  }

  /// 提交设置密码
  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

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

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

      // 判断是新流程还是旧流程
      if (widget.phoneNumber != null) {
        if (widget.skipVerify) {
          // 跳过验证流程：使用 register-without-sms-verify API
          debugPrint('[SetPasswordPage] 使用跳过验证流程: register-without-sms-verify');

          final response = await accountService.registerWithoutSmsVerify(
            phoneNumber: widget.phoneNumber!,
            password: password,
            inviterReferralCode: widget.inviterReferralCode,
          );

          debugPrint('[SetPasswordPage] 注册成功（跳过验证）: ${response.userSerialNum}');

          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('[SetPasswordPage] 已添加到多账号列表（跳过验证）');
        } else if (widget.smsCode != null) {
          // 新流程：使用 register-by-phone API 一步完成注册
          debugPrint('[SetPasswordPage] 使用新流程: register-by-phone');

          final response = await accountService.registerByPhoneWithPassword(
            phoneNumber: widget.phoneNumber!,
            smsCode: widget.smsCode!,
            password: password,
            inviterReferralCode: widget.inviterReferralCode,
          );

          debugPrint('[SetPasswordPage] 注册成功: ${response.userSerialNum}');

          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('[SetPasswordPage] 已添加到多账号列表');
        } else {
          throw Exception('缺少验证码');
        }
      } else {
        // 旧流程：单独设置密码
        debugPrint('[SetPasswordPage] 使用旧流程: set-password');
        await accountService.setLoginPassword(password);
        debugPrint('[SetPasswordPage] 密码设置成功');
      }

      if (!mounted) return;

      // 刷新 AuthProvider 状态（读取新保存的 isAccountCreated）
      await ref.read(authProvider.notifier).loadAuthState();
      debugPrint('[SetPasswordPage] AuthProvider 状态已刷新');

      if (!mounted) return;

      // 跳转到主页
      context.go(RoutePaths.mining);
    } catch (e) {
      debugPrint('[SetPasswordPage] 设置密码失败: $e');
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @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(
          '设置登录密码',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: const Color(0xFF333333),
          ),
        ),
        centerTitle: true,
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: SafeArea(
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Form(
              key: _formKey,
              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(
                    '密码需包含6-20位字母和数字',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: const Color(0xFF999999),
                    ),
                  ),
                  SizedBox(height: 32.h),
                  // 密码输入框
                  _buildPasswordField(
                    controller: _passwordController,
                    label: '登录密码',
                    hint: '请输入密码',
                    isPasswordVisible: _isPasswordVisible,
                    onToggleVisibility: () {
                      setState(() {
                        _isPasswordVisible = !_isPasswordVisible;
                      });
                    },
                    validator: _validatePassword,
                  ),
                  SizedBox(height: 16.h),
                  // 确认密码输入框
                  _buildPasswordField(
                    controller: _confirmPasswordController,
                    label: '确认密码',
                    hint: '请再次输入密码',
                    isPasswordVisible: _isConfirmPasswordVisible,
                    onToggleVisibility: () {
                      setState(() {
                        _isConfirmPasswordVisible = !_isConfirmPasswordVisible;
                      });
                    },
                    validator: _validateConfirmPassword,
                  ),
                  // 错误信息
                  if (_errorMessage != null) ...[
                    SizedBox(height: 16.h),
                    Container(
                      padding: EdgeInsets.all(12.w),
                      decoration: BoxDecoration(
                        color: Colors.red.withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: Row(
                        children: [
                          Icon(
                            Icons.error_outline,
                            color: Colors.red,
                            size: 20.sp,
                          ),
                          SizedBox(width: 8.w),
                          Expanded(
                            child: Text(
                              _errorMessage!,
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: Colors.red,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                  SizedBox(height: 40.h),
                  // 提交按钮
                  GestureDetector(
                    onTap: _isSubmitting ? null : _submit,
                    child: Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      decoration: BoxDecoration(
                        color: _isSubmitting
                            ? const Color(0xFFCCCCCC)
                            : const Color(0xFF2E7D32),
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: _isSubmitting
                          ? Center(
                              child: SizedBox(
                                width: 24.sp,
                                height: 24.sp,
                                child: const CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                    Colors.white,
                                  ),
                                ),
                              ),
                            )
                          : Text(
                              '完成注册',
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w600,
                                color: Colors.white,
                              ),
                              textAlign: TextAlign.center,
                            ),
                    ),
                  ),
                  SizedBox(height: 32.h),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPasswordField({
    required TextEditingController controller,
    required String label,
    required String hint,
    required bool isPasswordVisible,
    required VoidCallback onToggleVisibility,
    required String? Function(String?) validator,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: const Color(0xFF333333),
          ),
        ),
        SizedBox(height: 8.h),
        TextFormField(
          controller: controller,
          obscureText: !isPasswordVisible,
          validator: validator,
          decoration: InputDecoration(
            hintText: hint,
            hintStyle: TextStyle(
              fontSize: 16.sp,
              color: const Color(0xFF999999),
            ),
            filled: true,
            fillColor: const Color(0xFFF5F5F5),
            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,
              ),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: const BorderSide(
                color: Colors.red,
                width: 2,
              ),
            ),
            contentPadding: EdgeInsets.symmetric(
              horizontal: 16.w,
              vertical: 16.h,
            ),
            suffixIcon: IconButton(
              icon: Icon(
                isPasswordVisible ? Icons.visibility_off : Icons.visibility,
                color: const Color(0xFF999999),
              ),
              onPressed: onToggleVisibility,
            ),
          ),
          style: TextStyle(
            fontSize: 16.sp,
            color: const Color(0xFF333333),
          ),
        ),
      ],
    );
  }
}
