import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:tanami_app/core/styles/app_text.dart';
import '../../../../core/utils/secure/secure_storage_service.dart';

part 'pin_event.dart';
part 'pin_state.dart';

class PinBloc extends Bloc<PinEvent, PinState> {
  final SecureStorageService secureStorageService;

  PinBloc({required this.secureStorageService})
      : super(const PinState(
            pin: '',
            pinComplete: false,
            isVerified: false,
            error: '',
            verifiedOnce: false)) {
    on<NumberPressed>((event, emit) {
      final newPin = state.pin + event.number;

      if (newPin.length <= 6) {
        emit(state.copyWith(
            pin: newPin,
            pinComplete: newPin.length == 6,
            error: '',
            verifiedOnce: false));

        if (newPin.length == 6) {
          add(VerifyPinPressed(newPin));
        }
      }
    });

    on<BackspacePressed>((event, emit) {
      if (state.pin.isNotEmpty) {
        final newPin = state.pin.substring(0, state.pin.length - 1);
        emit(state.copyWith(
            pin: newPin,
            pinComplete: newPin.length == 6,
            error: '',
            verifiedOnce: false));
      }
    });

    on<SavePinPressed>((event, emit) async {
      await secureStorageService.write('pin_code', state.pin);
    });

    on<VerifyPinPressed>((event, emit) async {
      final storedPin = await secureStorageService.read('pin_code');

      if (storedPin == event.pin) {
        emit(state.copyWith(isVerified: true, error: '', verifiedOnce: true));
      } else {
        emit(state.copyWith(
          isVerified: false,
          error: AppText.incorrectPinCode,
          verifiedOnce: true,
        ));
      }
    });
  }
}
