import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../repositories/reset_password_repository.dart';

part 'reset_password_event.dart';
part 'reset_password_state.dart';

class ResetPasswordBloc extends Bloc<ResetPasswordEvent, ResetPasswordState> {
  final ResetPasswordRepository _resetPasswordRepository;

  ResetPasswordBloc({ResetPasswordRepository? resetPasswordRepository})
      : _resetPasswordRepository =
            resetPasswordRepository ?? ResetPasswordRepository(),
        super(const ResetPasswordState()) {
    on<ResetPasswordSubmitted>(_onResetPasswordSubmitted);
    on<ResetPasswordVisibilityToggled>(_onResetPasswordVisibilityToggled);
    on<ConfirmPasswordVisibilityToggled>(_onConfirmPasswordVisibilityToggled);
    on<PasswordChanged>(_onPasswordChanged);
    on<ResetPasswordErrorToggled>(_onPasswordErrorToggled);
    on<ResetConfirmPasswordErrorToggled>(_onConfirmPasswordErrorToggled);
  }

  Future<void> _onResetPasswordSubmitted(
    ResetPasswordSubmitted event,
    Emitter<ResetPasswordState> emit,
  ) async {
    emit(state.copyWith(
        status: ResetPasswordStatus.loading, errorMessage: null));

    try {
      await _resetPasswordRepository.resetPassword(
        emailAddress: event.emailAddress,
        newPassword: event.newPassword,
      );

      emit(state.copyWith(status: ResetPasswordStatus.success));
    } catch (e) {
      emit(state.copyWith(
        status: ResetPasswordStatus.failure,
        errorMessage: e.toString().replaceAll('Exception: ', ''),
      ));
    }
  }

  void _onResetPasswordVisibilityToggled(
    ResetPasswordVisibilityToggled event,
    Emitter<ResetPasswordState> emit,
  ) {
    emit(state.copyWith(isPasswordVisible: !state.isPasswordVisible));
  }

  void _onConfirmPasswordVisibilityToggled(
    ConfirmPasswordVisibilityToggled event,
    Emitter<ResetPasswordState> emit,
  ) {
    emit(state.copyWith(
        isConfirmPasswordVisible: !state.isConfirmPasswordVisible));
  }

  void _onPasswordChanged(
    PasswordChanged event,
    Emitter<ResetPasswordState> emit,
  ) {
    final password = event.password;
    emit(state.copyWith(
      hasMinLength: password.length >= 8,
      hasUppercase: password.contains(RegExp(r'[A-Z]')),
      hasLowercase: password.contains(RegExp(r'[a-z]')),
      hasNumber: password.contains(RegExp(r'[0-9]')),
      hasSpecial: password.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]')),
    ));
  }

  void _onPasswordErrorToggled(
    ResetPasswordErrorToggled event,
    Emitter<ResetPasswordState> emit,
  ) {
    emit(state.copyWith(
      showPasswordError: event.show,
      passwordErrorText: event.error,
    ));
  }

  void _onConfirmPasswordErrorToggled(
    ResetConfirmPasswordErrorToggled event,
    Emitter<ResetPasswordState> emit,
  ) {
    emit(state.copyWith(
      showConfirmPasswordError: event.show,
      confirmPasswordErrorText: event.error,
    ));
  }
}
