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

import 'restore_password_event.dart';
import 'restore_password_state.dart';

class RestorePasswordBloc
    extends Bloc<RestorePasswordEvent, RestorePasswordState> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController passwordTextField = TextEditingController();
  final TextEditingController repeatPasswordTextField = TextEditingController();

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

  RestorePasswordBloc() : super(RestorePasswordInitial()) {
    passwordTextField.addListener(_onFormFieldChanged);
    repeatPasswordTextField.addListener(_onFormFieldChanged);
    on<RestorePasswordFormChanged>(_onLoginFormChanged);
    on<RestorePasswordSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        return;
      }
      emit(RestorePasswordLoading());
      try {
        // Simulate API call
        await Future.delayed(const Duration(seconds: 2));
        // Replace the next line with actual API call
        final isSuccess = await _mockLoginApi(event.password);
        if (isSuccess) {
          emit(RestorePasswordSuccess());
        } else {
          emit(const RestorePasswordFailure(
              "Failed. Please check your credentials."));
        }
      } catch (e) {
        emit(RestorePasswordFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(RestorePasswordFormChanged(
      passwordTextField.text,
      repeatPasswordTextField.text,
    ));
  }

  void _onLoginFormChanged(
      RestorePasswordFormChanged event, Emitter<RestorePasswordState> emit) {
    final areFieldsFilled =
        event.password.isNotEmpty && event.repeatPassword.isNotEmpty;
    emit(RestorePasswordFieldsState(areFieldsFilled));
  }

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

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

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

    return super.close();
  }
}
