import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../domain/arguments/get_time_cards_arguments.dart';
import '../../domain/usecases/get_time_cards_usecase.dart';

part 'time_card_event.dart';
part 'time_card_state.dart';

/// BLoC to manage Time Card state.
class TimeCardBloc extends Bloc<TimeCardEvent, TimeCardState> {
  final GetTimeCardsUseCase getTimeCards;
  
  TimeCardBloc({required this.getTimeCards}) : super(TimeCardInitial()) {
    on<LoadTimeCards>(_onLoadTimeCards);
    on<ChangeMonth>(_onChangeMonth);
  }

  /// Handles fetching time cards for the requested month.
  Future<void> _onLoadTimeCards(LoadTimeCards event, Emitter<TimeCardState> emit) async {
    emit(TimeCardLoading());
    try {
      final List<TimeCard> cards = await getTimeCards(GetTimeCardsArguments(event.month));
      
      final double totalHours = cards.fold(0.0, (double sum, TimeCard t) => sum + t.totalHours);
      final double totalEarnings = cards.fold(0.0, (double sum, TimeCard t) => sum + t.totalPay);

      emit(TimeCardLoaded(
        timeCards: cards,
        selectedMonth: event.month,
        totalHours: totalHours,
        totalEarnings: totalEarnings,
      ));
    } catch (e) {
      emit(TimeCardError(e.toString()));
    }
  }
  
  Future<void> _onChangeMonth(ChangeMonth event, Emitter<TimeCardState> emit) async {
      add(LoadTimeCards(event.month));
  }
}
