import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../config/app_config.dart';
import '../../../data/services/state_service.dart';
import '../../../data/services/bridge_service.dart';
import '../../../injection_container.dart';
import 'monitor_event.dart';
import 'monitor_state.dart';

class MonitorBloc extends Bloc<MonitorEvent, MonitorBlocState> {
  final StateService _stateService;
  final AppConfig _config;
  StreamSubscription? _stateSubscription;

  MonitorBloc({
    required StateService stateService,
    required AppConfig config,
  })  : _stateService = stateService,
        _config = config,
        super(MonitorBlocState(availableMonitors: config.allMonitorIds)) {
    on<SelectMonitor>(_onSelectMonitor);
    on<ClearMonitor>(_onClearMonitor);
    on<ClearMonitorSelection>(_onClearMonitorSelection);
    on<MonitorStatesUpdated>(_onMonitorStatesUpdated);

    // Subscribe to monitor state changes
    _stateSubscription = _stateService.combinedMonitorStates.listen((states) {
      add(MonitorStatesUpdated(states));
    });
  }

  void _onSelectMonitor(
    SelectMonitor event,
    Emitter<MonitorBlocState> emit,
  ) {
    emit(state.copyWith(selectedMonitorId: event.monitorId, error: null));
  }

  Future<void> _onClearMonitor(
    ClearMonitor event,
    Emitter<MonitorBlocState> emit,
  ) async {
    try {
      final bridgeService = sl<BridgeService>();
      await bridgeService.viewerClear(event.monitorId);
    } catch (e) {
      emit(state.copyWith(error: 'Failed to clear monitor: $e'));
    }
  }

  void _onClearMonitorSelection(
    ClearMonitorSelection event,
    Emitter<MonitorBlocState> emit,
  ) {
    emit(state.copyWith(clearSelection: true, error: null));
  }

  void _onMonitorStatesUpdated(
    MonitorStatesUpdated event,
    Emitter<MonitorBlocState> emit,
  ) {
    emit(state.copyWith(monitorStates: event.states));
  }

  @override
  Future<void> close() {
    _stateSubscription?.cancel();
    return super.close();
  }
}
