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

import 'restore_password_phone_verification_event.dart';
import 'restore_password_phone_verification_state.dart';

class RestorePasswordPhoneVerificationBloc extends Bloc<
    RestorePasswordPhoneVerificationEvent,
    RestorePasswordPhoneVerificationState> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController phoneNumberTextField = TextEditingController();
  final TextEditingController countrySelectionTextField =
      TextEditingController();

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

  RestorePasswordPhoneVerificationBloc()
      : super(RestorePasswordPhoneVerificationInitial()) {
    phoneNumberTextField.addListener(_onFormFieldChanged);
    countrySelectionTextField.addListener(_onFormFieldChanged);
    on<RestorePasswordPhoneVerificationFormChanged>(_onLoginFormChanged);
    on<RestorePasswordPhoneVerificationSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        return;
      }
      emit(RestorePasswordPhoneVerificationLoading());
      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);
        if (isSuccess) {
          emit(RestorePasswordPhoneVerificationSuccess());
        } else {
          emit(const RestorePasswordPhoneVerificationFailure(
              "Failed. Please check your credentials."));
        }
      } catch (e) {
        emit(RestorePasswordPhoneVerificationFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(RestorePasswordPhoneVerificationFormChanged(
      phoneNumberTextField.text,
      countrySelectionTextField.text,
    ));
  }

  void _onLoginFormChanged(RestorePasswordPhoneVerificationFormChanged event,
      Emitter<RestorePasswordPhoneVerificationState> emit) {
    final areFieldsFilled =
        event.phoneNumber.isNotEmpty && event.country.isNotEmpty;
    emit(RestorePasswordPhoneVerificationFieldsState(areFieldsFilled));
  }

  // Method to reset text fields
  void resetFields() {
    phoneNumberTextField.clear();
    countrySelectionTextField.clear();
  }

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

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

    return super.close();
  }
}
