import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

import '../../repository/submit_qr_code_repository.dart';

part 'submit_qr_code_event.dart';
part 'submit_qr_code_state.dart';

class SubmitQrCodeBloc
    extends Bloc<SubmitQrCodeEvent, SubmitQrCodeState> {
  final SubmitQrCodeRepository _repository;

  SubmitQrCodeBloc({SubmitQrCodeRepository? repository})
      : _repository = repository ?? SubmitQrCodeRepository(),
        super(const SubmitQrCodeInitial()) {
    on<SubmitQrCodeEventTriggered>(_onSubmitQrCode);
    on<ResetSubmitQrCodeEvent>(_onReset);
  }

  Future<void> _onSubmitQrCode(
      SubmitQrCodeEventTriggered event,
      Emitter<SubmitQrCodeState> emit,
      ) async {
    if (event.qrCode.trim().isEmpty) {
      emit(const SubmitQrCodeFailure(
          errorMessage: 'QR code cannot be empty'));
      return;
    }

    emit(const SubmitQrCodeLoading());

    try {
      final response = await _repository.submitQrCode(
        qrCode: event.qrCode,
      );

      final success = response['success'] == true;
      final message = response['message']?.toString();
      final error = response['error']?.toString();

      if (success) {
        emit(SubmitQrCodeSuccess(
          data: response,
          message: message,
        ));
      } else {
        emit(SubmitQrCodeFailure(
          errorMessage: message ?? 'Failed to submit QR Code',
          error: error,
        ));
      }

    } on Exception catch (e) {
      emit(SubmitQrCodeFailure(
        errorMessage: e.toString().replaceFirst('Exception: ', ''),
      ));
    } catch (e) {
      emit(SubmitQrCodeFailure(
        errorMessage: 'Unexpected error: $e',
      ));
    }
  }

  void _onReset(
      ResetSubmitQrCodeEvent event,
      Emitter<SubmitQrCodeState> emit,
      ) {
    emit(const SubmitQrCodeInitial());
  }
}