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

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController countrySelectionTextField =
      TextEditingController();
  final TextEditingController phoneNumberTextField = TextEditingController();
  final TextEditingController passwordTextField = TextEditingController();

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

  LoginBloc() : super(LoginInitial()) {
    phoneNumberTextField.addListener(_onFormFieldChanged);
    passwordTextField.addListener(_onFormFieldChanged);
    countrySelectionTextField.addListener(_onFormFieldChanged);
    on<LoginFormChanged>(_onLoginFormChanged);
    on<LoginSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        emit(
            const LoginFailure("Login failed. Please check your credentials."));
        return;
      }
      emit(LoginLoading());
      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.password, event.countryResidence);
        if (isSuccess) {
          emit(LoginSuccess());
        } else {
          emit(const LoginFailure(
              "Login failed. Please check your credentials."));
        }
      } catch (e) {
        emit(LoginFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(LoginFormChanged(
      phoneNumberTextField.text,
      passwordTextField.text,
      countrySelectionTextField.text,
    ));
  }

  void _onLoginFormChanged(LoginFormChanged event, Emitter<LoginState> emit) {
    final areFieldsFilled = event.phoneNumber.isNotEmpty &&
        event.password.isNotEmpty &&
        event.country.isNotEmpty;
    emit(LoginFieldsState(areFieldsFilled));
  }

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

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

  @override
  Future<void> close() {
    phoneNumberTextField.dispose();
    passwordTextField.dispose();
    countrySelectionTextField.dispose();
    return super.close();
  }
}
