import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';
import '../../../../shared/widgets/genex_button.dart';
import '../../../../shared/widgets/countdown_button.dart';
import '../../../../core/services/auth_service.dart';
import '../../../../app/i18n/app_localizations.dart';

/// A1. 忘记密码 - 手机号验证 → 输入验证码 → 设置新密码 → 成功
class ForgotPasswordPage extends StatefulWidget {
  const ForgotPasswordPage({super.key});

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

class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
  int _step = 0; // 0: 输入账号, 1: 验证码, 2: 新密码, 3: 成功
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmController = TextEditingController();
  bool _obscurePassword = true;
  bool _obscureConfirm = true;
  bool _loading = false;
  String? _errorMessage;

  final _authService = AuthService.instance;

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _passwordController.dispose();
    _confirmController.dispose();
    super.dispose();
  }

  String _extractError(DioException e) {
    final data = e.response?.data;
    if (data is Map && data['message'] != null) {
      return data['message'].toString();
    }
    return context.t('login.networkError');
  }

  /* ── Step 0: 发送验证码 ── */
  Future<void> _handleSendCode() async {
    final phone = _phoneController.text.trim();
    if (phone.isEmpty) {
      setState(() => _errorMessage = context.t('register.errorPhoneRequired'));
      throw Exception('phone required');
    }
    setState(() => _errorMessage = null);
    try {
      await _authService.sendSmsCode(phone, SmsCodeType.resetPassword);
      setState(() => _step = 1);
    } on DioException catch (e) {
      setState(() => _errorMessage = _extractError(e));
      rethrow;
    }
  }

  /* ── Step 1 → Step 2 ── */
  void _handleCodeNext() {
    if (_codeController.text.trim().length != 6) {
      setState(() => _errorMessage = context.t('register.errorCodeInvalid'));
      return;
    }
    setState(() { _step = 2; _errorMessage = null; });
  }

  /* ── Step 2: 重设密码 ── */
  Future<void> _handleResetPassword() async {
    final password = _passwordController.text;
    final confirm = _confirmController.text;

    if (password.length < 8) {
      setState(() => _errorMessage = context.t('login.errorPasswordMin'));
      return;
    }
    if (password != confirm) {
      setState(() => _errorMessage = context.t('forgot.errorPasswordMismatch'));
      return;
    }

    setState(() { _loading = true; _errorMessage = null; });
    try {
      await _authService.resetPassword(
        phone: _phoneController.text.trim(),
        smsCode: _codeController.text.trim(),
        newPassword: password,
      );
      setState(() => _step = 3);
    } on DioException catch (e) {
      setState(() => _errorMessage = _extractError(e));
    } catch (e) {
      setState(() => _errorMessage = e.toString());
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  /* ── Step 1: 重新发送 ── */
  Future<void> _handleResend() async {
    try {
      await _authService.sendSmsCode(
        _phoneController.text.trim(),
        SmsCodeType.resetPassword,
      );
    } on DioException catch (e) {
      setState(() => _errorMessage = _extractError(e));
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_step == 3 ? '' : context.t('forgot.title')),
        leading: _step == 3
            ? const SizedBox.shrink()
            : IconButton(
                icon: const Icon(Icons.arrow_back_ios_rounded, size: 20),
                onPressed: () {
                  if (_step > 0 && _step < 3) {
                    setState(() { _step--; _errorMessage = null; });
                  } else {
                    Navigator.pop(context);
                  }
                },
              ),
      ),
      body: SafeArea(
        child: Padding(
          padding: AppSpacing.pagePadding,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Error message
              if (_errorMessage != null) ...[
                const SizedBox(height: 8),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  decoration: BoxDecoration(
                    color: AppColors.errorLight,
                    borderRadius: AppSpacing.borderRadiusSm,
                  ),
                  child: Row(
                    children: [
                      const Icon(Icons.error_outline, color: AppColors.error, size: 18),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          _errorMessage!,
                          style: AppTypography.bodySmall.copyWith(color: AppColors.error),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
              Expanded(child: _buildStep()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStep() {
    switch (_step) {
      case 0:
        return _buildStepAccount();
      case 1:
        return _buildStepCode();
      case 2:
        return _buildStepPassword();
      case 3:
        return _buildStepSuccess();
      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildStepAccount() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 24),
        Text(context.t('forgot.inputAccount'), style: AppTypography.h1),
        const SizedBox(height: 8),
        Text(
          context.t('forgot.sendHint'),
          style: AppTypography.bodyMedium.copyWith(color: AppColors.textSecondary),
        ),
        const SizedBox(height: 32),
        TextField(
          controller: _phoneController,
          keyboardType: TextInputType.phone,
          decoration: InputDecoration(
            hintText: context.t('forgot.accountHint'),
            prefixIcon: const Icon(Icons.person_outline_rounded),
          ),
        ),
        const SizedBox(height: 24),
        CountdownButton(
          label: context.t('forgot.getCode'),
          onPressed: _handleSendCode,
        ),
      ],
    );
  }

  Widget _buildStepCode() {
    final phone = _phoneController.text.trim();
    final masked = phone.length >= 7
        ? '${phone.substring(0, 3)}****${phone.substring(phone.length - 4)}'
        : phone;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 24),
        Text(context.t('forgot.inputCode'), style: AppTypography.h1),
        const SizedBox(height: 8),
        Text(
          '${context.t('forgot.codeSentTo')} $masked',
          style: AppTypography.bodyMedium.copyWith(color: AppColors.textSecondary),
        ),
        const SizedBox(height: 32),
        TextField(
          controller: _codeController,
          keyboardType: TextInputType.number,
          maxLength: 6,
          decoration: InputDecoration(
            hintText: context.t('forgot.codeHint'),
            counterText: '',
            prefixIcon: const Icon(Icons.lock_outline_rounded),
          ),
        ),
        const SizedBox(height: 16),
        Align(
          alignment: Alignment.centerRight,
          child: CountdownButton(
            label: context.t('forgot.resend'),
            onPressed: _handleResend,
          ),
        ),
        const SizedBox(height: 8),
        GenexButton(
          label: context.t('forgot.next'),
          onPressed: _handleCodeNext,
        ),
      ],
    );
  }

  Widget _buildStepPassword() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 24),
        Text(context.t('forgot.setNewPassword'), style: AppTypography.h1),
        const SizedBox(height: 8),
        Text(
          context.t('forgot.newPasswordHint'),
          style: AppTypography.bodyMedium.copyWith(color: AppColors.textSecondary),
        ),
        const SizedBox(height: 32),
        TextField(
          controller: _passwordController,
          obscureText: _obscurePassword,
          decoration: InputDecoration(
            hintText: context.t('forgot.newPassword'),
            prefixIcon: const Icon(Icons.lock_outline_rounded),
            suffixIcon: IconButton(
              icon: Icon(_obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined),
              onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
            ),
          ),
        ),
        const SizedBox(height: 16),
        TextField(
          controller: _confirmController,
          obscureText: _obscureConfirm,
          decoration: InputDecoration(
            hintText: context.t('forgot.confirmPassword'),
            prefixIcon: const Icon(Icons.lock_outline_rounded),
            suffixIcon: IconButton(
              icon: Icon(_obscureConfirm ? Icons.visibility_off_outlined : Icons.visibility_outlined),
              onPressed: () => setState(() => _obscureConfirm = !_obscureConfirm),
            ),
          ),
        ),
        const SizedBox(height: 24),
        GenexButton(
          label: context.t('forgot.confirmChange'),
          isLoading: _loading,
          onPressed: _handleResetPassword,
        ),
      ],
    );
  }

  Widget _buildStepSuccess() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 80,
            height: 80,
            decoration: const BoxDecoration(
              color: AppColors.successLight,
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.check_rounded, color: AppColors.success, size: 40),
          ),
          const SizedBox(height: 24),
          Text(context.t('forgot.success'), style: AppTypography.h1),
          const SizedBox(height: 8),
          Text(
            context.t('forgot.successHint'),
            style: AppTypography.bodyMedium.copyWith(color: AppColors.textSecondary),
          ),
          const SizedBox(height: 40),
          SizedBox(
            width: double.infinity,
            child: GenexButton(
              label: context.t('forgot.backToLogin'),
              onPressed: () => Navigator.of(context).pushNamedAndRemoveUntil('/login', (_) => false),
            ),
          ),
        ],
      ),
    );
  }
}
