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

/// 重置支付密码页面 [2026-03-05]
///
/// 流程：发送短信验证码（发送到当前账号绑定手机）→ 输入验证码 → 设置新 6 位支付密码
///
/// 与 [ForgotPasswordPage]（找回登录密码）的区别：
/// - 无需输入手机号（用户已登录，手机号由后端从 JWT 获取）
/// - 密码格式为 6 位纯数字（登录密码无此限制）
///
/// 后端接口：
/// - POST /user/send-reset-payment-password-sms → 发送验证码
/// - POST /user/reset-payment-password → { smsCode, newPassword } → 重置
class ResetPaymentPasswordPage extends ConsumerStatefulWidget {
  const ResetPaymentPasswordPage({super.key});

  @override
  ConsumerState<ResetPaymentPasswordPage> createState() =>
      _ResetPaymentPasswordPageState();
}

class _ResetPaymentPasswordPageState
    extends ConsumerState<ResetPaymentPasswordPage> {
  final TextEditingController _smsCodeController = TextEditingController();
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();

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

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _smsCodeController.dispose();
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  /// 发送短信验证码（无需传手机号，后端从 JWT 取）
  Future<void> _sendSmsCode() async {
    setState(() {
      _isSendingSms = true;
      _errorMessage = null;
    });

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

      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) {
      if (mounted) {
        setState(() {
          _isSendingSms = false;
          _errorMessage = '发送失败：$e';
        });
      }
    }
  }

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

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

    if (smsCode.isEmpty) return '请输入短信验证码';
    if (smsCode.length != 6) return '验证码为6位数字';
    if (newPassword.isEmpty) return '请输入新支付密码';
    if (!RegExp(r'^\d{6}$').hasMatch(newPassword)) 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 accountService = ref.read(accountServiceProvider);
      await accountService.resetPaymentPassword(
        smsCode: _smsCodeController.text.trim(),
        newPassword: _newPasswordController.text,
      );

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('支付密码重置成功'),
            backgroundColor: Color(0xFF4CAF50),
            duration: Duration(seconds: 2),
          ),
        );
        // 重置成功后返回上一页
        context.pop();
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    }
  }

  // ============================================================
  // Build
  // ============================================================

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFFF7E6),
      appBar: _buildAppBar(),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 24.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _buildInfoCard(),
              SizedBox(height: 24.h),
              _buildFormCard(),
              if (_errorMessage != null) ...[
                SizedBox(height: 12.h),
                _buildErrorMessage(),
              ],
              SizedBox(height: 32.h),
              _buildSubmitButton(),
            ],
          ),
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: const Color(0xFFFFF7E6),
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF5D4037)),
        onPressed: () => context.pop(),
      ),
      title: const Text(
        '忘记支付密码',
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.w600,
          color: Color(0xFF5D4037),
        ),
      ),
      centerTitle: true,
    );
  }

  /// 说明卡片
  Widget _buildInfoCard() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF3CD),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0xFFFFD700).withValues(alpha: 0.5)),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Icon(Icons.info_outline, color: Color(0xFFD4AF37), size: 20),
          SizedBox(width: 10.w),
          const Expanded(
            child: Text(
              '验证码将发送到您绑定的手机号，验证后可设置新的6位数字支付密码',
              style: TextStyle(
                fontSize: 13,
                color: Color(0xFF5D4037),
                height: 1.5,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 表单卡片
  Widget _buildFormCard() {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF8B5A2B).withValues(alpha: 0.08),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSmsCodeField(),
          SizedBox(height: 16.h),
          _buildPasswordField(
            controller: _newPasswordController,
            label: '新支付密码',
            hint: '请输入6位数字',
            obscure: _obscureNewPassword,
            onToggleObscure: () =>
                setState(() => _obscureNewPassword = !_obscureNewPassword),
          ),
          SizedBox(height: 16.h),
          _buildPasswordField(
            controller: _confirmPasswordController,
            label: '确认新支付密码',
            hint: '请再次输入6位数字',
            obscure: _obscureConfirmPassword,
            onToggleObscure: () => setState(
                () => _obscureConfirmPassword = !_obscureConfirmPassword),
          ),
        ],
      ),
    );
  }

  /// 验证码输入框（含发送按钮）
  Widget _buildSmsCodeField() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '短信验证码',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: Color(0xFF5D4037),
          ),
        ),
        SizedBox(height: 8.h),
        Row(
          children: [
            Expanded(
              child: Container(
                height: 48.h,
                decoration: BoxDecoration(
                  color: const Color(0xFFFFF7E6),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: const Color(0x4D8B5A2B)),
                ),
                child: TextField(
                  controller: _smsCodeController,
                  keyboardType: TextInputType.number,
                  maxLength: 6,
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  onChanged: (_) {
                    if (_errorMessage != null) {
                      setState(() => _errorMessage = null);
                    }
                  },
                  style: const TextStyle(
                    fontSize: 16,
                    color: Color(0xFF5D4037),
                  ),
                  decoration: const InputDecoration(
                    contentPadding:
                        EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                    border: InputBorder.none,
                    hintText: '请输入6位验证码',
                    hintStyle: TextStyle(
                      fontSize: 14,
                      color: Color(0x995D4037),
                    ),
                    counterText: '',
                  ),
                ),
              ),
            ),
            SizedBox(width: 10.w),
            _buildSendSmsButton(),
          ],
        ),
      ],
    );
  }

  Widget _buildSendSmsButton() {
    final canSend = !_isSendingSms && _countdown == 0;
    return GestureDetector(
      onTap: canSend ? _sendSmsCode : null,
      child: Container(
        height: 48.h,
        padding: EdgeInsets.symmetric(horizontal: 12.w),
        decoration: BoxDecoration(
          color: canSend ? const Color(0xFFD4AF37) : const Color(0xFFE0D5C5),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Center(
          child: _isSendingSms
              ? const SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor:
                        AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : Text(
                  _countdown > 0 ? '${_countdown}s后重发' : '发送验证码',
                  style: TextStyle(
                    fontSize: 13,
                    color: canSend ? Colors.white : const Color(0xFF9E8B7A),
                    fontWeight: FontWeight.w500,
                  ),
                ),
        ),
      ),
    );
  }

  /// 密码输入框（含显示/隐藏切换）
  Widget _buildPasswordField({
    required TextEditingController controller,
    required String label,
    required String hint,
    required bool obscure,
    required VoidCallback onToggleObscure,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: Color(0xFF5D4037),
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          height: 48.h,
          decoration: BoxDecoration(
            color: const Color(0xFFFFF7E6),
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: const Color(0x4D8B5A2B)),
          ),
          child: TextField(
            controller: controller,
            obscureText: obscure,
            keyboardType: TextInputType.number,
            maxLength: 6,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly],
            onChanged: (_) {
              if (_errorMessage != null) setState(() => _errorMessage = null);
            },
            style: const TextStyle(fontSize: 16, color: Color(0xFF5D4037)),
            decoration: InputDecoration(
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
              border: InputBorder.none,
              hintText: hint,
              hintStyle: const TextStyle(
                fontSize: 14,
                color: Color(0x995D4037),
              ),
              counterText: '',
              suffixIcon: GestureDetector(
                onTap: onToggleObscure,
                child: Icon(
                  obscure ? Icons.visibility_off : Icons.visibility,
                  color: const Color(0xFF8B5A2B),
                  size: 20,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildErrorMessage() {
    return Row(
      children: [
        const Icon(Icons.error_outline, size: 14, color: Color(0xFFFF4D4F)),
        SizedBox(width: 4.w),
        Expanded(
          child: Text(
            _errorMessage!,
            style: const TextStyle(fontSize: 12, color: Color(0xFFFF4D4F)),
          ),
        ),
      ],
    );
  }

  Widget _buildSubmitButton() {
    final smsCode = _smsCodeController.text.trim();
    final newPassword = _newPasswordController.text;
    final confirmPassword = _confirmPasswordController.text;
    final canSubmit = !_isSubmitting &&
        smsCode.length == 6 &&
        newPassword.length == 6 &&
        confirmPassword.length == 6;

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