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

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

part 'register_form_event.dart';
part 'register_form_state.dart';
part 'register_form_bloc.freezed.dart';

@injectable
class RegisterFormBloc extends Bloc<RegisterFormEvent, RegisterFormState> {
  final IAuthRepository _repository;
  RegisterFormBloc(this._repository) : super(RegisterFormState.initial()) {
    on<RegisterFormEvent>(_onRegisterFormEvent);
  }

  Future<void> _onRegisterFormEvent(
    RegisterFormEvent event,
    Emitter<RegisterFormState> emit,
  ) {
    return event.map(
      phoneNumberChanged: (e) async {
        emit(
          state.copyWith(
            phoneNumber: e.phoneNumber,
            failureOrRegisterOption: none(),
          ),
        );
      },
      nameChanged: (e) async {
        emit(state.copyWith(name: e.name, failureOrRegisterOption: none()));
      },
      birthDateChanged: (e) async {
        emit(
          state.copyWith(
            birthDate: e.birthDate,
            failureOrRegisterOption: none(),
          ),
        );
      },
      submitted: (e) async {
        Either<AuthFailure, Register>? failureOrRegister;
        emit(
          state.copyWith(isSubmitting: true, failureOrRegisterOption: none()),
        );

        final phoneNumberValid = state.phoneNumber.isNotEmpty;
        final nameValid = state.name.isNotEmpty;

        if (phoneNumberValid && nameValid) {
          failureOrRegister = await _repository.register(
            phoneNumber: state.phoneNumber,
            name: state.name,
            birthDate: state.birthDate,
          );
          emit(
            state.copyWith(
              isSubmitting: false,
              failureOrRegisterOption: optionOf(failureOrRegister),
            ),
          );
        }
        emit(state.copyWith(showErrorMessages: true, isSubmitting: false));
      },
    );
  }
}
