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

import 'register_user_event.dart';
import 'register_user_state.dart';

class RegisterUserBloc extends Bloc<RegisterUserEvent, RegisterUserState> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController firstNameTextField = TextEditingController();
  final TextEditingController lastNameTextField = TextEditingController();
  final TextEditingController emailTextField = TextEditingController();
  final TextEditingController passwordTextField = TextEditingController();
  final TextEditingController repeatPasswordTextField = TextEditingController();

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

  RegisterUserBloc() : super(RegisterUserInitial()) {
    firstNameTextField.addListener(_onFormFieldChanged);
    passwordTextField.addListener(_onFormFieldChanged);
    lastNameTextField.addListener(_onFormFieldChanged);
    emailTextField.addListener(_onFormFieldChanged);
    repeatPasswordTextField.addListener(_onFormFieldChanged);

    on<RegisterFormChanged>(_onLoginFormChanged);
    on<RegisterUserSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        return;
      }
      emit(RegisterUserLoading());
      try {
        // Simulate API call
        await Future.delayed(const Duration(seconds: 2));
        // Replace the next line with actual API call
        final isSuccess = await _mockLoginApi(
          event.firstName,
          event.password,
          event.lastName,
          event.confirmPassword,
          event.email,
        );
        if (isSuccess) {
          emit(RegisterUserSuccess());
        } else {
          emit(const RegisterUserFailure(
              "Register failed. Please check your credentials."));
        }
      } catch (e) {
        emit(RegisterUserFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(RegisterFormChanged(
      firstNameTextField.text,
      lastNameTextField.text,
      emailTextField.text,
      passwordTextField.text,
      repeatPasswordTextField.text,
    ));
  }

  void _onLoginFormChanged(
      RegisterFormChanged event, Emitter<RegisterUserState> emit) {
    final areFieldsFilled = event.firstName.isNotEmpty &&
        event.lastName.isNotEmpty &&
        event.email.isNotEmpty &&
        event.password.isNotEmpty &&
        event.confirmPassword.isNotEmpty;
    emit(RegisterUserFieldsState(areFieldsFilled));
  }

  // Mock API function, replace with actual API call
  Future<bool> _mockLoginApi(
    String firstName,
    String password,
    String confirmPassword,
    String email,
    String lastName,
  ) async {
    return true;
  }

  @override
  Future<void> close() {
    firstNameTextField.dispose();
    passwordTextField.dispose();
    lastNameTextField.dispose();
    emailTextField.dispose();
    repeatPasswordTextField.dispose();
    return super.close();
  }
}
