import 'package:bloc/bloc.dart';
import 'package:dartz/dartz.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/user/user.dart';

part 'change_password_form_event.dart';
part 'change_password_form_state.dart';
part 'change_password_form_bloc.freezed.dart';

@injectable
class ChangePasswordFormBloc
    extends Bloc<ChangePasswordFormEvent, ChangePasswordFormState> {
  final IUserRepository _repository;
  ChangePasswordFormBloc(this._repository)
    : super(ChangePasswordFormState.initial()) {
    on<ChangePasswordFormEvent>(_onChangePasswordFormEvent);
  }

  Future<void> _onChangePasswordFormEvent(
    ChangePasswordFormEvent event,
    Emitter<ChangePasswordFormState> emit,
  ) {
    return event.map(
      newPasswordChanged: (e) async {
        emit(
          state.copyWith(
            newPassword: e.newPassword,
            failureOrChangePasswordOption: none(),
          ),
        );
      },
      currentPasswordChanged: (e) async {
        emit(
          state.copyWith(
            currentPassword: e.currentPassword,
            failureOrChangePasswordOption: none(),
          ),
        );
      },
      submitted: (e) async {
        Either<UserFailure, Unit>? failureOrSuccess;
        emit(
          state.copyWith(
            isSubmitting: true,
            failureOrChangePasswordOption: none(),
          ),
        );

        final oldPasswordValid = state.newPassword.isNotEmpty;
        final currentPasswordValid = state.currentPassword.isNotEmpty;

        if (oldPasswordValid && currentPasswordValid) {
          failureOrSuccess = await _repository.changePassword(
            newPassword: state.newPassword,
            currentPassword: state.currentPassword,
          );
          emit(
            state.copyWith(
              isSubmitting: false,
              failureOrChangePasswordOption: optionOf(failureOrSuccess),
            ),
          );
        }
        emit(state.copyWith(showErrorMessages: true, isSubmitting: false));
      },
    );
  }
}
