import 'package:bloc/bloc.dart';
import '../../../domain/usecases/apply_for_shift_usecase.dart';
import '../../../domain/usecases/decline_shift_usecase.dart';
import '../../../domain/usecases/get_shift_details_usecase.dart';
import 'shift_details_event.dart';
import 'shift_details_state.dart';

class ShiftDetailsBloc extends Bloc<ShiftDetailsEvent, ShiftDetailsState> {
  final GetShiftDetailsUseCase getShiftDetails;
  final ApplyForShiftUseCase applyForShift;
  final DeclineShiftUseCase declineShift;

  ShiftDetailsBloc({
    required this.getShiftDetails,
    required this.applyForShift,
    required this.declineShift,
  }) : super(ShiftDetailsInitial()) {
    on<LoadShiftDetailsEvent>(_onLoadDetails);
    on<BookShiftDetailsEvent>(_onBookShift);
    on<DeclineShiftDetailsEvent>(_onDeclineShift);
  }

  Future<void> _onLoadDetails(
    LoadShiftDetailsEvent event,
    Emitter<ShiftDetailsState> emit,
  ) async {
    emit(ShiftDetailsLoading());
    try {
      final shift = await getShiftDetails(event.shiftId);
      if (shift != null) {
        emit(ShiftDetailsLoaded(shift));
      } else {
        emit(const ShiftDetailsError("Shift not found"));
      }
    } catch (e) {
      emit(ShiftDetailsError(e.toString()));
    }
  }

  Future<void> _onBookShift(
    BookShiftDetailsEvent event,
    Emitter<ShiftDetailsState> emit,
  ) async {
    try {
      await applyForShift(event.shiftId, isInstantBook: true);
      emit(const ShiftActionSuccess("Shift successfully booked!"));
    } catch (e) {
      emit(ShiftDetailsError(e.toString()));
    }
  }

  Future<void> _onDeclineShift(
    DeclineShiftDetailsEvent event,
    Emitter<ShiftDetailsState> emit,
  ) async {
    try {
      await declineShift(event.shiftId);
      emit(const ShiftActionSuccess("Shift declined"));
    } catch (e) {
      emit(ShiftDetailsError(e.toString()));
    }
  }
}
