// otp_bloc.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sms_autofill/sms_autofill.dart';
import 'otp_event.dart';
import 'otp_state.dart';

class OtpBloc extends Bloc<OtpEvent, OtpState> {
  final TextEditingController otpController = TextEditingController();
  OtpBloc() : super(OtpInitial()) {
    on<StartListeningForOtp>(_onStartListeningForOtp);
    on<OtpCodeChanged>(_onOtpCodeChanged);
    on<OtpSubmit>(_onOtpSubmit);
  }

  void _onStartListeningForOtp(
      StartListeningForOtp event, Emitter<OtpState> emit) {
    _startListening();
  }

  void _onOtpCodeChanged(OtpCodeChanged event, Emitter<OtpState> emit) {
    emit(OtpCodeReceived(event.code));
    if (event.code.length == 6) {
      add(OtpSubmit(event.code));
    }
  }

  void _onOtpSubmit(OtpSubmit event, Emitter<OtpState> emit) async {
    emit(OtpSubmitting());
    try {
      // Add your OTP verification logic here
      await Future.delayed(const Duration(seconds: 2));
      if (otpController.text == "123456") {
        emit(OtpSubmissionSuccess());
      } else {
        emit(const OtpSubmissionFailure("Otp Invalid !"));
      } // Simulate network call
    } catch (e) {
      emit(OtpSubmissionFailure(e.toString()));
    }
  }

  void _startListening() {
    SmsAutoFill().listenForCode(); // Correctly call listenForCode
  }

  @override
  Future<void> close() {
    otpController.dispose();
    SmsAutoFill().unregisterListener();
    return super.close();
  }
}
