import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';

import 'deposit_payment_event.dart';
import 'deposit_payment_state.dart';

class DepositPaymentBloc
    extends Bloc<DepositPaymentEvent, DepositPaymentState> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  TextEditingController amountController = TextEditingController();

  GlobalKey<FormState> getFormKey() {
    return formKey;
  }

  DepositPaymentBloc()
      : super(const DepositPaymentState(isFormValid: false, amount: '0')) {
    on<FormTextChanged>((event, emit) {
      final isFormValid = event.text.isNotEmpty;
      emit(state.copyWith(
          isFormValid: isFormValid,
          amount: event.text.isEmpty ? "0" : event.text));
    });

    // Ensure the listener is added in the constructor
    amountController.addListener(() {
      add(FormTextChanged(text: amountController.text));
    });
  }

  @override
  Future<void> close() {
    amountController.dispose();

    return super.close();
  }
}
