import 'package:flutter_bloc/flutter_bloc.dart';
import '../../repositories/balance_repository.dart';
import '../../repositories/expense_repository.dart';
import '../../services/balance_service.dart';
import '../../services/error_service.dart';
import 'balance_event.dart';
import 'balance_state.dart';
class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
  final BalanceRepository _balanceRepository;
  final BalanceService _balanceService;
  final ErrorService _errorService;

  BalanceBloc({
    required BalanceRepository balanceRepository,
    required ExpenseRepository expenseRepository,
    BalanceService? balanceService,
    ErrorService? errorService,
  }) : _balanceRepository = balanceRepository,
       _balanceService = balanceService ?? BalanceService(balanceRepository: balanceRepository, expenseRepository: expenseRepository),
       _errorService = errorService ?? ErrorService(),
       super(BalanceInitial()) {
    on<LoadGroupBalance>(_onLoadGroupBalance);
    on<RefreshBalance>(_onRefreshBalance);
    on<MarkSettlementAsCompleted>(_onMarkSettlementAsCompleted);
  }

  Future<void> _onLoadGroupBalance(
    LoadGroupBalance event,
    Emitter<BalanceState> emit,
  ) async {
    try {
      emit(BalanceLoading());
      
      final groupBalance = await _balanceRepository.calculateGroupBalance(event.groupId);
      emit(BalanceLoaded(groupBalance));
    } catch (e) {
      _errorService.logError('BalanceBloc', 'Erreur chargement balance: $e');
      emit(BalanceError(e.toString()));
    }
  }

  Future<void> _onRefreshBalance(
    RefreshBalance event,
    Emitter<BalanceState> emit,
  ) async {
    try {
      // Garde l'état actuel pendant le refresh si possible
      if (state is! BalanceLoaded) {
        emit(BalanceLoading());
      }
      
      final groupBalance = await _balanceRepository.calculateGroupBalance(event.groupId);
      emit(BalanceLoaded(groupBalance));
    } catch (e) {
      _errorService.logError('BalanceBloc', 'Erreur refresh balance: $e');
      emit(BalanceError(e.toString()));
    }
  }

  Future<void> _onMarkSettlementAsCompleted(
    MarkSettlementAsCompleted event,
    Emitter<BalanceState> emit,
  ) async {
    try {
      await _balanceService.markSettlementAsCompleted(
        groupId: event.groupId,
        fromUserId: event.fromUserId,
        toUserId: event.toUserId,
        amount: event.amount,
      );
      
      emit(const BalanceOperationSuccess('Règlement marqué comme effectué'));
      
      // Recharger la balance après le règlement
      add(RefreshBalance(event.groupId));
    } catch (e) {
      _errorService.logError('BalanceBloc', 'Erreur mark settlement: $e');
      emit(BalanceError(e.toString()));
    }
  }
}