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

class PaymentsBloc extends Bloc<PaymentsEvent, PaymentsState> {
  final GetPaymentSummaryUseCase getPaymentSummary;
  final GetPaymentHistoryUseCase getPaymentHistory;

  PaymentsBloc({
    required this.getPaymentSummary,
    required this.getPaymentHistory,
  }) : super(PaymentsInitial()) {
    on<LoadPaymentsEvent>(_onLoadPayments);
    on<ChangePeriodEvent>(_onChangePeriod);
  }

  Future<void> _onLoadPayments(
    LoadPaymentsEvent event,
    Emitter<PaymentsState> emit,
  ) async {
    emit(PaymentsLoading());
    try {
      final List<StaffPayment> allPayments = await getPaymentSummary();
      final PaymentStats stats = _calculateStats(allPayments);
      
      final List<StaffPayment> history = await getPaymentHistory(
        const GetPaymentHistoryArguments('week'),
      );
      emit(PaymentsLoaded(
        summary: stats,
        history: history,
        activePeriod: 'week',
      ));
    } catch (e) {
      emit(PaymentsError(e.toString()));
    }
  }

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

  PaymentStats _calculateStats(List<StaffPayment> payments) {
    double total = 0;
    double pending = 0;
    double weekly = 0;
    double monthly = 0;
    
    final DateTime now = DateTime.now();
    
    for (final StaffPayment p in payments) {
      // Assuming all payments count towards total history
      total += p.amount;
      
      if (p.status == PaymentStatus.pending) {
        pending += p.amount;
      }
      
      if (p.paidAt != null) {
        if (now.difference(p.paidAt!).inDays < 7) {
          weekly += p.amount;
        }
        if (now.month == p.paidAt!.month && now.year == p.paidAt!.year) {
          monthly += p.amount;
        }
      }
    }
    
    return PaymentStats(
      totalEarnings: total,
      pendingEarnings: pending,
      weeklyEarnings: weekly,
      monthlyEarnings: monthly,
    );
  }
}
