import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow_core/core.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../../domain/arguments/get_payment_history_arguments.dart';
import '../../../domain/usecases/get_payment_history_usecase.dart';
import '../../../domain/usecases/get_payment_summary_usecase.dart';
import 'payments_event.dart';
import 'payments_state.dart';

class PaymentsBloc extends Bloc<PaymentsEvent, PaymentsState>
    with BlocErrorHandler<PaymentsState> {
  PaymentsBloc({
    required this.getPaymentSummary,
    required this.getPaymentHistory,
  }) : super(PaymentsInitial()) {
    on<LoadPaymentsEvent>(_onLoadPayments);
    on<ChangePeriodEvent>(_onChangePeriod);
  }
  final GetPaymentSummaryUseCase getPaymentSummary;
  final GetPaymentHistoryUseCase getPaymentHistory;

  Future<void> _onLoadPayments(
    LoadPaymentsEvent event,
    Emitter<PaymentsState> emit,
  ) async {
    emit(PaymentsLoading());
    await handleError(
      emit: emit,
      action: () async {
        final PaymentSummary currentSummary = await getPaymentSummary();

        final List<StaffPayment> history = await getPaymentHistory(
          const GetPaymentHistoryArguments('week'),
        );
        emit(
          PaymentsLoaded(
            summary: currentSummary,
            history: history,
            activePeriod: 'week',
          ),
        );
      },
      onError: (String errorKey) => PaymentsError(errorKey),
    );
  }

  Future<void> _onChangePeriod(
    ChangePeriodEvent event,
    Emitter<PaymentsState> emit,
  ) async {
    final PaymentsState currentState = state;
    if (currentState is PaymentsLoaded) {
      await handleError(
        emit: emit,
        action: () async {
          final List<StaffPayment> newHistory = await getPaymentHistory(
            GetPaymentHistoryArguments(event.period),
          );
          emit(
            currentState.copyWith(
              history: newHistory,
              activePeriod: event.period,
            ),
          );
        },
        onError: (String errorKey) => PaymentsError(errorKey),
      );
    }
  }
}

