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

class RegisterBloc extends Bloc<RegisterEvent, RegisterState> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController countrySelectionTextField =
      TextEditingController();
  final TextEditingController phoneNumberTextField = TextEditingController();

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

  RegisterBloc() : super(RegisterInitial()) {
    phoneNumberTextField.addListener(_onFormFieldChanged);

    countrySelectionTextField.addListener(_onFormFieldChanged);
    on<RegisterFormChanged>(_onLoginFormChanged);
    on<RegisterSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        return;
      }
      emit(RegisterLoading());
      try {
        // Simulate API call
        await Future.delayed(const Duration(seconds: 2));
        // Replace the next line with actual API call
        final isSuccess =
            await _mockLoginApi(event.phoneNumber, event.countryResidence);
        if (isSuccess) {
          emit(RegisterSuccess());
        } else {
          emit(const RegisterFailure(
              "Register failed. Please check your credentials."));
        }
      } catch (e) {
        emit(RegisterFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(RegisterFormChanged(
      phoneNumberTextField.text,
      countrySelectionTextField.text,
    ));
  }

  void _onLoginFormChanged(
      RegisterFormChanged event, Emitter<RegisterState> emit) {
    final areFieldsFilled =
        event.phoneNumber.isNotEmpty && event.country.isNotEmpty;
    emit(RegisterFieldsState(areFieldsFilled));
  }

  // Mock API function, replace with actual API call
  Future<bool> _mockLoginApi(
    String phoneNumber,
    String countryResidence,
  ) async {
    return true;
  }

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

    countrySelectionTextField.dispose();
    return super.close();
  }
}
