import 'package:flutter_bloc/flutter_bloc.dart';

/// EVENTS
abstract class ResetPasswordEvent {}

class PasswordChanged extends ResetPasswordEvent {
  final String password;
  PasswordChanged(this.password);
}

class ConfirmPasswordChanged extends ResetPasswordEvent {
  final String confirmPassword;
  ConfirmPasswordChanged(this.confirmPassword);
}

/// STATE
class ResetPasswordState {
  final String password;
  final String confirmPassword;
  final bool hasMinLength;
  final bool hasUppercase;
  final bool hasNumber;
  final int strengthLevel; // 0–4 based on password strength

  const ResetPasswordState({
    required this.password,
    required this.confirmPassword,
    required this.hasMinLength,
    required this.hasUppercase,
    required this.hasNumber,
    required this.strengthLevel,
  });

  factory ResetPasswordState.initial() => const ResetPasswordState(
    password: '',
    confirmPassword: '',
    hasMinLength: false,
    hasUppercase: false,
    hasNumber: false,
    strengthLevel: 0,
  );

  ResetPasswordState copyWith({
    String? password,
    String? confirmPassword,
    bool? hasMinLength,
    bool? hasUppercase,
    bool? hasNumber,
    int? strengthLevel,
  }) {
    return ResetPasswordState(
      password: password ?? this.password,
      confirmPassword: confirmPassword ?? this.confirmPassword,
      hasMinLength: hasMinLength ?? this.hasMinLength,
      hasUppercase: hasUppercase ?? this.hasUppercase,
      hasNumber: hasNumber ?? this.hasNumber,
      strengthLevel: strengthLevel ?? this.strengthLevel,
    );
  }
}

/// BLOC
class ResetPasswordBloc extends Bloc<ResetPasswordEvent, ResetPasswordState> {
  ResetPasswordBloc() : super(ResetPasswordState.initial()) {
    on<PasswordChanged>((event, emit) {
      final pwd = event.password;
      final hasMin = pwd.length >= 8;
      final hasUp = pwd.contains(RegExp(r'[A-Z]'));
      final hasNum = pwd.contains(RegExp(r'[0-9]'));

      // count how many validations passed (max 3)
      int passed = [hasMin, hasUp, hasNum].where((e) => e).length;

      // convert to 4-box level (0–4)
      int level = 0;
      if (passed == 1) level = 1;
      if (passed == 2) level = 2;
      if (passed == 3) level = 4; // all conditions passed => full bar

      emit(state.copyWith(
        password: pwd,
        hasMinLength: hasMin,
        hasUppercase: hasUp,
        hasNumber: hasNum,
        strengthLevel: level,
      ));
    });

    on<ConfirmPasswordChanged>((event, emit) {
      emit(state.copyWith(confirmPassword: event.confirmPassword));
    });
  }
}
