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

import '../../../common/function/app_function.dart';
import '../../../domain/auth/auth.dart';

part 'check_phone_form_event.dart';
part 'check_phone_form_state.dart';
part 'check_phone_form_bloc.freezed.dart';

@injectable
class CheckPhoneFormBloc
    extends Bloc<CheckPhoneFormEvent, CheckPhoneFormState> {
  final IAuthRepository _repository;
  CheckPhoneFormBloc(this._repository) : super(CheckPhoneFormState.initial()) {
    on<CheckPhoneFormEvent>(_onCheckPhoneFormEvent);
  }

  Future<void> _onCheckPhoneFormEvent(
    CheckPhoneFormEvent event,
    Emitter<CheckPhoneFormState> emit,
  ) {
    return event.map(
      phoneNumberChanged: (e) async {
        emit(
          state.copyWith(
            phoneNumber: e.phoneNumber,
            failureOrCheckPhoneOption: none(),
          ),
        );
      },
      submitted: (e) async {
        Either<AuthFailure, CheckPhone>? failureOrCheckPhone;
        emit(
          state.copyWith(isSubmitting: true, failureOrCheckPhoneOption: none()),
        );

        final phoneNumberValid = state.phoneNumber.isNotEmpty;

        if (phoneNumberValid) {
          failureOrCheckPhone = await _repository.checkPhone(
            phoneNumber: getNormalizePhone(state.phoneNumber),
          );
          emit(
            state.copyWith(
              isSubmitting: false,
              failureOrCheckPhoneOption: optionOf(failureOrCheckPhone),
            ),
          );
        }
        emit(state.copyWith(showErrorMessages: true, isSubmitting: false));
      },
    );
  }
}
