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 'resend_form_event.dart';
part 'resend_form_state.dart';
part 'resend_form_bloc.freezed.dart';

@injectable
class ResendFormBloc extends Bloc<ResendFormEvent, ResendFormState> {
  final IAuthRepository _repository;
  ResendFormBloc(this._repository) : super(ResendFormState.initial()) {
    on<ResendFormEvent>(_onResendFormEvent);
  }

  Future<void> _onResendFormEvent(
    ResendFormEvent event,
    Emitter<ResendFormState> emit,
  ) {
    return event.map(
      phoneNumberChanged: (e) async {
        emit(
          state.copyWith(
            phoneNumber: e.phoneNumber,
            failureOrResendOption: none(),
          ),
        );
      },
      purposeChanged: (e) async {
        emit(state.copyWith(purpose: e.purpose, failureOrResendOption: none()));
      },
      submitted: (e) async {
        Either<AuthFailure, Resend>? failureOrResend;
        emit(state.copyWith(isSubmitting: true, failureOrResendOption: none()));

        final phoneNumberValid = state.phoneNumber.isNotEmpty;
        final purposeValid = state.purpose.isNotEmpty;

        if (phoneNumberValid && purposeValid) {
          failureOrResend = await _repository.resend(
            phoneNumber: state.phoneNumber,
            purpose: state.purpose,
          );

          emit(
            state.copyWith(
              isSubmitting: false,
              failureOrResendOption: optionOf(failureOrResend),
            ),
          );
        }
        emit(state.copyWith(showErrorMessages: true, isSubmitting: false));
      },
    );
  }
}
