import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/arguments/rapid_order_arguments.dart';
import '../../domain/usecases/create_rapid_order_usecase.dart';
import 'rapid_order_event.dart';
import 'rapid_order_state.dart';

/// BLoC for managing the rapid (urgent) order creation flow.
class RapidOrderBloc extends Bloc<RapidOrderEvent, RapidOrderState> {
  RapidOrderBloc(this._createRapidOrderUseCase)
    : super(
        const RapidOrderInitial(
          examples: <String>[
            '"We had a call out. Need 2 cooks ASAP"',
            '"Need 5 bartenders ASAP until 5am"',
            '"Emergency! Need 3 servers right now till midnight"',
          ],
        ),
      ) {
    on<RapidOrderMessageChanged>(_onMessageChanged);
    on<RapidOrderVoiceToggled>(_onVoiceToggled);
    on<RapidOrderSubmitted>(_onSubmitted);
    on<RapidOrderExampleSelected>(_onExampleSelected);
  }
  final CreateRapidOrderUseCase _createRapidOrderUseCase;

  void _onMessageChanged(
    RapidOrderMessageChanged event,
    Emitter<RapidOrderState> emit,
  ) {
    if (state is RapidOrderInitial) {
      emit((state as RapidOrderInitial).copyWith(message: event.message));
    }
  }

  Future<void> _onVoiceToggled(
    RapidOrderVoiceToggled event,
    Emitter<RapidOrderState> emit,
  ) async {
    if (state is RapidOrderInitial) {
      final RapidOrderInitial currentState = state as RapidOrderInitial;
      final bool newListeningState = !currentState.isListening;

      emit(currentState.copyWith(isListening: newListeningState));

      // Simulate voice recognition
      if (newListeningState) {
        await Future<void>.delayed(const Duration(seconds: 2));
        if (state is RapidOrderInitial) {
          emit(
            (state as RapidOrderInitial).copyWith(
              message: 'Need 2 servers for a banquet right now.',
              isListening: false,
            ),
          );
        }
      }
    }
  }

  Future<void> _onSubmitted(
    RapidOrderSubmitted event,
    Emitter<RapidOrderState> emit,
  ) async {
    final RapidOrderState currentState = state;
    if (currentState is RapidOrderInitial) {
      final String message = currentState.message;
      print('RapidOrder submit: message="$message"');
      emit(const RapidOrderSubmitting());

      try {
        await _createRapidOrderUseCase(
          RapidOrderArguments(description: message),
        );
        print('RapidOrder submit: success');
        emit(const RapidOrderSuccess());
      } catch (e) {
        print('RapidOrder submit: error=$e');
        emit(RapidOrderFailure(e.toString()));
      }
    }
  }

  void _onExampleSelected(
    RapidOrderExampleSelected event,
    Emitter<RapidOrderState> emit,
  ) {
    if (state is RapidOrderInitial) {
      final String cleanedExample = event.example.replaceAll('"', '');
      emit((state as RapidOrderInitial).copyWith(message: cleanedExample));
    }
  }
}
