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/user/user.dart';

part 'user_edit_form_event.dart';
part 'user_edit_form_state.dart';
part 'user_edit_form_bloc.freezed.dart';

@injectable
class UserEditFormBloc extends Bloc<UserEditFormEvent, UserEditFormState> {
  final IUserRepository _repository;
  UserEditFormBloc(this._repository) : super(UserEditFormState.initial()) {
    on<UserEditFormEvent>(_onUserEditFormEvent);
  }

  Future<void> _onUserEditFormEvent(
    UserEditFormEvent event,
    Emitter<UserEditFormState> emit,
  ) {
    return event.map(
      nameChanged: (e) async {
        emit(state.copyWith(name: e.name, failureOrUserOption: none()));
      },
      submitted: (e) async {
        Either<UserFailure, User>? failureOrUser;
        emit(state.copyWith(isSubmitting: true, failureOrUserOption: none()));

        final nameValid = state.name.isNotEmpty;

        if (nameValid) {
          failureOrUser = await _repository.editUser(name: state.name);
          emit(
            state.copyWith(
              isSubmitting: false,
              failureOrUserOption: optionOf(failureOrUser),
            ),
          );
        }
        emit(state.copyWith(showErrorMessages: true, isSubmitting: false));
      },
    );
  }
}
