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';

/// 找回密码页面
/// 通过手机号+短信验证码重置密码
class ForgotPasswordPage extends ConsumerStatefulWidget {
  const ForgotPasswordPage({super.key});

  @override
  ConsumerState<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends ConsumerState<ForgotPasswordPage> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _smsCodeController = TextEditingController();
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController();

  bool _isSubmitting = false;
  bool _isSendingSms = false;
  int _countdown = 0;
  String? _errorMessage;
  bool _obscureNewPassword = true;
  bool _obscureConfirmPassword = true;

  @override
  void dispose() {
    _phoneController.dispose();
    _smsCodeController.dispose();
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  /// 验证手机号格式
  bool _isValidPhoneNumber(String phone) {
    final regex = RegExp(r'^1[3-9]\d{9}$');
    return regex.hasMatch(phone);
  }

  /// 发送短信验证码
  Future<void> _sendSmsCode() async {
    final phone = _phoneController.text.trim();

    if (phone.isEmpty) {
      setState(() => _errorMessage = '请输入手机号');
      return;
    }

    if (!_isValidPhoneNumber(phone)) {
      setState(() => _errorMessage = '请输入正确的手机号');
      return;
    }

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

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

      if (mounted) {
        setState(() {
          _isSendingSms = false;
          _countdown = 60;
        });
        _startCountdown();

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('验证码已发送'),
            backgroundColor: Color(0xFF4CAF50),
            duration: Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      debugPrint('[ForgotPasswordPage] 发送验证码失败: $e');
      if (mounted) {
        setState(() {
          _isSendingSms = false;
          _errorMessage = '发送验证码失败，请稍后重试';
        });
      }
    }
  }

  /// 开始倒计时
  void _startCountdown() {
    Future.doWhile(() async {
      await Future.delayed(const Duration(seconds: 1));
      if (!mounted || _countdown <= 0) return false;
      setState(() {
        _countdown--;
      });
      return _countdown > 0;
    });
  }

  /// 验证输入
  String? _validateInputs() {
    final phone = _phoneController.text.trim();
    final smsCode = _smsCodeController.text.trim();
    final newPassword = _newPasswordController.text;
    final confirmPassword = _confirmPasswordController.text;

    if (phone.isEmpty) return '请输入手机号';
    if (!_isValidPhoneNumber(phone)) return '请输入正确的手机号';
    if (smsCode.isEmpty) return '请输入验证码';
    if (smsCode.length != 6) return '验证码为6位数字';
    if (newPassword.isEmpty) return '请输入新密码';
    if (newPassword.length < 6) return '密码至少6位';
    if (confirmPassword.isEmpty) return '请确认新密码';
    if (newPassword != confirmPassword) return '两次输入的密码不一致';

    return null;
  }

  /// 重置密码
  Future<void> _resetPassword() async {
    final validationError = _validateInputs();
    if (validationError != null) {
      setState(() => _errorMessage = validationError);
      return;
    }

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

    try {
      final phone = _phoneController.text.trim();
      final smsCode = _smsCodeController.text.trim();
      final newPassword = _newPasswordController.text;

      final accountService = ref.read(accountServiceProvider);
      await accountService.resetPassword(
        phoneNumber: phone,
        smsCode: smsCode,
        newPassword: newPassword,
      );

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('密码重置成功，请重新登录'),
            backgroundColor: Color(0xFF4CAF50),
            duration: Duration(seconds: 2),
          ),
        );
        context.pop();
      }
    } catch (e) {
      debugPrint('[ForgotPasswordPage] 重置密码失败: $e');
      setState(() {
        _errorMessage = '重置密码失败: $e';
      });
    } finally {
      if (mounted) {
        setState(() => _isSubmitting = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF5E6),
              Color(0xFFEAE0C8),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildAppBar(),
              Expanded(
                child: GestureDetector(
                  onTap: () => FocusScope.of(context).unfocus(),
                  child: SingleChildScrollView(
                    padding: EdgeInsets.symmetric(horizontal: 24.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 32.h),
                        _buildPhoneInput(),
                        SizedBox(height: 16.h),
                        _buildSmsCodeInput(),
                        SizedBox(height: 16.h),
                        _buildNewPasswordInput(),
                        SizedBox(height: 16.h),
                        _buildConfirmPasswordInput(),
                        if (_errorMessage != null) ...[
                          SizedBox(height: 16.h),
                          _buildErrorMessage(),
                        ],
                        SizedBox(height: 32.h),
                        _buildSubmitButton(),
                        SizedBox(height: 32.h),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAppBar() {
    return Container(
      height: 56.h,
      padding: EdgeInsets.symmetric(horizontal: 8.w),
      child: Row(
        children: [
          IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF5D4037)),
            onPressed: () => context.pop(),
          ),
          Expanded(
            child: Text(
              '找回密码',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: const Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
          ),
          SizedBox(width: 48.w),
        ],
      ),
    );
  }

  Widget _buildPhoneInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '手机号',
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF5D4037),
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          padding: EdgeInsets.symmetric(vertical: 12.h),
          decoration: const BoxDecoration(
            border: Border(
              bottom: BorderSide(color: Color(0xFFD4A574), width: 1),
            ),
          ),
          child: TextField(
            controller: _phoneController,
            keyboardType: TextInputType.phone,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly,
              LengthLimitingTextInputFormatter(11),
            ],
            style: TextStyle(
              fontSize: 16.sp,
              color: const Color(0xFF5D4037),
              fontWeight: FontWeight.w500,
            ),
            decoration: InputDecoration(
              hintText: '请输入手机号',
              hintStyle: TextStyle(fontSize: 16.sp, color: const Color(0xFFB8956A)),
              border: InputBorder.none,
              isDense: false,
              contentPadding: EdgeInsets.zero,
            ),
            onChanged: (_) {
              if (_errorMessage != null) setState(() => _errorMessage = null);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildSmsCodeInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '验证码',
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF5D4037),
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          padding: EdgeInsets.symmetric(vertical: 12.h),
          decoration: const BoxDecoration(
            border: Border(
              bottom: BorderSide(color: Color(0xFFD4A574), width: 1),
            ),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _smsCodeController,
                  keyboardType: TextInputType.number,
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly,
                    LengthLimitingTextInputFormatter(6),
                  ],
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: const Color(0xFF5D4037),
                    fontWeight: FontWeight.w500,
                  ),
                  decoration: InputDecoration(
                    hintText: '请输入验证码',
                    hintStyle: TextStyle(fontSize: 16.sp, color: const Color(0xFFB8956A)),
                    border: InputBorder.none,
                    isDense: false,
                    contentPadding: EdgeInsets.zero,
                  ),
                  onChanged: (_) {
                    if (_errorMessage != null) setState(() => _errorMessage = null);
                  },
                ),
              ),
              GestureDetector(
                onTap: (_isSendingSms || _countdown > 0) ? null : _sendSmsCode,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
                  decoration: BoxDecoration(
                    color: (_isSendingSms || _countdown > 0)
                        ? const Color(0xFFD4C4B0)
                        : const Color(0xFF8B5A2B),
                    borderRadius: BorderRadius.circular(6.r),
                  ),
                  child: Text(
                    _isSendingSms
                        ? '发送中...'
                        : _countdown > 0
                            ? '${_countdown}s'
                            : '获取验证码',
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildNewPasswordInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '新密码',
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF5D4037),
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          padding: EdgeInsets.symmetric(vertical: 12.h),
          decoration: const BoxDecoration(
            border: Border(
              bottom: BorderSide(color: Color(0xFFD4A574), width: 1),
            ),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _newPasswordController,
                  obscureText: _obscureNewPassword,
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: const Color(0xFF5D4037),
                    fontWeight: FontWeight.w500,
                  ),
                  decoration: InputDecoration(
                    hintText: '请输入新密码（至少6位）',
                    hintStyle: TextStyle(fontSize: 16.sp, color: const Color(0xFFB8956A)),
                    border: InputBorder.none,
                    isDense: false,
                    contentPadding: EdgeInsets.zero,
                  ),
                  onChanged: (_) {
                    if (_errorMessage != null) setState(() => _errorMessage = null);
                  },
                ),
              ),
              GestureDetector(
                onTap: () => setState(() => _obscureNewPassword = !_obscureNewPassword),
                child: Icon(
                  _obscureNewPassword ? Icons.visibility_off : Icons.visibility,
                  color: const Color(0xFF8B6F47),
                  size: 20.sp,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildConfirmPasswordInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '确认新密码',
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF5D4037),
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          padding: EdgeInsets.symmetric(vertical: 12.h),
          decoration: const BoxDecoration(
            border: Border(
              bottom: BorderSide(color: Color(0xFFD4A574), width: 1),
            ),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _confirmPasswordController,
                  obscureText: _obscureConfirmPassword,
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: const Color(0xFF5D4037),
                    fontWeight: FontWeight.w500,
                  ),
                  decoration: InputDecoration(
                    hintText: '请再次输入新密码',
                    hintStyle: TextStyle(fontSize: 16.sp, color: const Color(0xFFB8956A)),
                    border: InputBorder.none,
                    isDense: false,
                    contentPadding: EdgeInsets.zero,
                  ),
                  onChanged: (_) {
                    if (_errorMessage != null) setState(() => _errorMessage = null);
                  },
                  onSubmitted: (_) => _resetPassword(),
                ),
              ),
              GestureDetector(
                onTap: () => setState(() => _obscureConfirmPassword = !_obscureConfirmPassword),
                child: Icon(
                  _obscureConfirmPassword ? Icons.visibility_off : Icons.visibility,
                  color: const Color(0xFF8B6F47),
                  size: 20.sp,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildErrorMessage() {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: Colors.red.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Colors.red.withOpacity(0.3), width: 1),
      ),
      child: Row(
        children: [
          Icon(Icons.error_outline, color: Colors.red, size: 16.sp),
          SizedBox(width: 8.w),
          Expanded(
            child: Text(
              _errorMessage!,
              style: TextStyle(fontSize: 14.sp, color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSubmitButton() {
    final canSubmit = !_isSubmitting &&
        _phoneController.text.trim().isNotEmpty &&
        _smsCodeController.text.trim().isNotEmpty &&
        _newPasswordController.text.isNotEmpty &&
        _confirmPasswordController.text.isNotEmpty;

    return SizedBox(
      width: double.infinity,
      height: 50.h,
      child: ElevatedButton(
        onPressed: canSubmit ? _resetPassword : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: canSubmit ? const Color(0xFF8B5A2B) : const Color(0xFFD4C4B0),
          disabledBackgroundColor: const Color(0xFFD4C4B0),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
          elevation: 0,
        ),
        child: _isSubmitting
            ? SizedBox(
                width: 20.w,
                height: 20.h,
                child: const CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              )
            : Text(
                '重置密码',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w700,
                  color: canSubmit ? Colors.white : const Color(0xFFB8956A),
                ),
              ),
      ),
    );
  }
}
