import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injectable/injectable.dart';
import '../../domain/usecases/get_staking_pools_usecase.dart';
import 'staking_event.dart';
import 'staking_state.dart';
import '../../domain/entities/staking_pool_entity.dart';

@singleton
class StakingBloc extends Bloc<StakingEvent, StakingState> {
  final GetStakingPoolsUseCase _getPoolsUseCase;
  bool _isLoadingInProgress = false;
  DateTime? _lastLoadTime;
  static const Duration _debounceDelay = Duration(milliseconds: 500);

  StakingBloc(this._getPoolsUseCase) : super(StakingInitial()) {
    on<LoadStakingData>(_onLoadData);
  }

  Future<void> _onLoadData(
    LoadStakingData event,
    Emitter<StakingState> emit,
  ) async {
    // Aggressive duplicate prevention
    final now = DateTime.now();

    // Prevent multiple calls if already loading
    if (_isLoadingInProgress) {
      print('🚫 STAKING_BLOC: Blocked duplicate call - already loading');
      return;
    }

    // Debounce rapid successive calls
    if (_lastLoadTime != null &&
        now.difference(_lastLoadTime!) < _debounceDelay) {
      print('🚫 STAKING_BLOC: Blocked rapid call - debouncing');
      return;
    }

    // If data is already loaded and no filters, don't reload
    if (state is StakingLoaded &&
        event.status == null &&
        event.minApr == null &&
        event.maxApr == null &&
        event.token == null) {
      print('🚫 STAKING_BLOC: Blocked call - data already loaded');
      return;
    }

    print('✅ STAKING_BLOC: Proceeding with API call');
    _isLoadingInProgress = true;
    _lastLoadTime = now;

    emit(StakingLoading());

    try {
      final params = GetStakingPoolsParams(
        status: event.status,
        minApr: event.minApr,
        maxApr: event.maxApr,
        token: event.token,
      );
      final result = await _getPoolsUseCase(params);
      result.fold(
        (failure) => emit(StakingError(failure.message)),
        (pools) => emit(StakingLoaded(pools: pools)),
      );
    } finally {
      _isLoadingInProgress = false;
    }
  }
}
