import 'package:bloc/bloc.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/core/entity/staff_contact_entity.dart';
import 'package:krow/features/rate_staff/data/rating_staff_repository.dart';
import 'package:meta/meta.dart';

part 'rating_staff_event.dart';
part 'rating_staff_state.dart';

class RatingStaffBloc extends Bloc<RatingStaffEvent, RatingStaffState> {
  RatingStaffBloc(StaffContact staff) : super(RatingStaffState(staff: staff, favorite: staff.isFavorite, blackListed: staff.isBlackListed)) {
    on<RatingChangedEvent>(_onRatingChanged);
    on<StaffFavoriteToggleEvent>(_onStaffFavoriteToggle);
    on<StaffBlacklistToggleEvent>(_onStaffBlacklistToggle);
    on<StaffReasonSelectedEvent>(_onStaffReasonSelected);
    on<StaffReasonDetailsChangeEvent>(_onStaffReasonDetailsChange);
    on<RatingSubmitEvent>(_onRatingSubmit);
  }

  void _onRatingChanged(RatingChangedEvent event, emit) {
    emit(state.copyWith(rating: event.rating));
  }

  void _onStaffFavoriteToggle(StaffFavoriteToggleEvent event, emit) {
    emit(state.copyWith(favorite: !state.favorite));
  }

  void _onStaffBlacklistToggle(StaffBlacklistToggleEvent event, emit) {
    emit(state.copyWith(blackListed: !state.blackListed));
  }

  void _onStaffReasonSelected(StaffReasonSelectedEvent event, emit) {
    emit(state.copyWith(reason: event.reason));
  }

  void _onStaffReasonDetailsChange(
      StaffReasonDetailsChangeEvent event, emit) {
    emit(state.copyWith(comment: event.details));
  }

  void _onRatingSubmit(RatingSubmitEvent event, emit) async {
    //todo change staff entity;
    try {
      await getIt<RatingStaffRepository>().rateStaff(
        positionId: state.staff.id,
        rating: state.rating,
        reason: state.reason,
        details: state.comment,
        isBlocked: state.blackListed,
        isFavorite: state.favorite,
      );
    } catch (e) {
      emit(state.copyWith(error: e.toString()));
      return;
    }
    state.staff.rating.value = state.rating.toDouble();
    emit(state.copyWith(success: true));
  }
}
