import 'package:flutter_bloc/flutter_bloc.dart';

// --------------------- EVENTS ---------------------
abstract class OtpEvent {}

/// Triggered when user types or pastes OTP
class OtpChanged extends OtpEvent {
  final String otp;
  OtpChanged(this.otp);
}

/// Triggered when user presses Verify button
class OtpVerify extends OtpEvent {}

/// (Optional for later) Triggered when user taps "Resend OTP"
class OtpResend extends OtpEvent {}


// --------------------- STATE ---------------------
class OtpState {
  final String otp;
  final bool isVerified;
  final bool isLoading;
  final bool isResending;
  final String message;

  /// Computed property to know if OTP input is complete (6 digits)
  bool get isOtpFilled => otp.length == 6;

  const OtpState({
    required this.otp,
    required this.isVerified,
    required this.isLoading,
    required this.isResending,
    required this.message,
  });

  OtpState copyWith({
    String? otp,
    bool? isVerified,
    bool? isLoading,
    bool? isResending,
    String? message,
  }) {
    return OtpState(
      otp: otp ?? this.otp,
      isVerified: isVerified ?? this.isVerified,
      isLoading: isLoading ?? this.isLoading,
      isResending: isResending ?? this.isResending,
      message: message ?? this.message,
    );
  }

  factory OtpState.initial() => const OtpState(
    otp: '',
    isVerified: false,
    isLoading: false,
    isResending: false,
    message: '',
  );
}


// --------------------- BLOC ---------------------
class OtpBloc extends Bloc<OtpEvent, OtpState> {
  OtpBloc() : super(OtpState.initial()) {
    // Handle typing input
    on<OtpChanged>((event, emit) {
      emit(state.copyWith(otp: event.otp, message: ''));
    });

    // Handle Verify
    on<OtpVerify>((event, emit) async {
      if (!state.isOtpFilled) return; // no action if OTP incomplete

      emit(state.copyWith(isLoading: true, message: ''));

      await Future.delayed(const Duration(seconds: 2)); // simulate API delay

      // Mock success condition — replace with API later
      if (state.otp == "123456") {
        emit(state.copyWith(
          isVerified: true,
          isLoading: false,
          message: "OTP verified successfully!",
        ));
      } else {
        emit(state.copyWith(
          isVerified: false,
          isLoading: false,
          message: "Invalid OTP. Please try again.",
        ));
      }
    });

    // Handle Resend OTP (optional for later)
    on<OtpResend>((event, emit) async {
      emit(state.copyWith(isResending: true, message: 'Resending OTP...'));
      await Future.delayed(const Duration(seconds: 3)); // simulate resend
      emit(state.copyWith(isResending: false, message: 'OTP resent successfully!'));
    });
  }
}
