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

import 'change_password_event.dart';
import 'change_password_state.dart';

class ChangePasswordBloc
    extends Bloc<ChangePasswordEvent, ChangePasswordState> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  final TextEditingController currentPasswordTextField =
      TextEditingController();
  final TextEditingController passwordTextField = TextEditingController();
  final TextEditingController repeatPasswordTextField = TextEditingController();

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

  ChangePasswordBloc() : super(ChangePasswordInitial()) {
    currentPasswordTextField.addListener(_onFormFieldChanged);
    passwordTextField.addListener(_onFormFieldChanged);
    repeatPasswordTextField.addListener(_onFormFieldChanged);
    on<ChangePasswordFormChanged>(_onLoginFormChanged);
    on<ChangePasswordSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        return;
      }
      emit(ChangePasswordLoading());
      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(ChangePasswordSuccess());
        } else {
          emit(const ChangePasswordFailure(
              "Failed. Please check your credentials."));
        }
      } catch (e) {
        emit(ChangePasswordFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(ChangePasswordFormChanged(
      currentPasswordTextField.text,
      passwordTextField.text,
      repeatPasswordTextField.text,
    ));
  }

  void _onLoginFormChanged(
      ChangePasswordFormChanged event, Emitter<ChangePasswordState> emit) {
    final areFieldsFilled = event.currentPassword.isNotEmpty &&
        event.password.isNotEmpty &&
        event.repeatPassword.isNotEmpty;
    emit(ChangePasswordFieldsState(areFieldsFilled));
  }

  // Method to reset text fields
  void resetFields() {
    currentPasswordTextField.clear();
    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();
    currentPasswordTextField.dispose();
    repeatPasswordTextField.dispose();

    return super.close();
  }
}
