// ignore: depend_on_referenced_packages;
import 'package:dartz/dartz.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/auth/auth.dart';

part 'login_form_event.dart';
part 'login_form_state.dart';
part 'login_form_bloc.freezed.dart';

@injectable
class LoginFormBloc extends Bloc<LoginFormEvent, LoginFormState> {
  final IAuthRepository _repository;
  LoginFormBloc(this._repository) : super(LoginFormState.initial()) {
    on<LoginFormEvent>(_onLoginFormEvent);
  }

  Future<void> _onLoginFormEvent(
    LoginFormEvent event,
    Emitter<LoginFormState> emit,
  ) {
    return event.map(
      emailChanged: (e) async {
        emit(state.copyWith(email: e.email));
      },
      passwordChanged: (e) async {
        emit(state.copyWith(password: e.password));
      },
      submitted: (e) async {
        Either<AuthFailure, Auth>? failureOrAuth;
        emit(state.copyWith(isSubmitting: true, failureOrAuthOption: none()));

        final emailValid = state.email.isNotEmpty;
        final passwordValid = state.password.isNotEmpty;

        if (emailValid && passwordValid) {
          failureOrAuth = await _repository.login(
            email: state.email,
            password: state.password,
          );
          emit(
            state.copyWith(
              isSubmitting: false,
              failureOrAuthOption: optionOf(failureOrAuth),
            ),
          );
        }
        emit(state.copyWith(showErrorMessages: true, isSubmitting: false));
      },
    );
  }
}
