import 'dart:developer';

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

import '../../../../Api_Helper/base_manager.dart';
import '../../domain/repository/forgot_password_api.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 {
        log(Globalconst.token);
        Map<String, dynamic> dataForm = {
          "code": Globalconst.token,
          "password_hash": event.password
        };
        ResponseData response =
            await ForgotPasswordApi().resetPasswordApi(dataForm);

        if (response.status == ResponseStatus.SUCCESS) {
          emit(RestorePasswordSuccess());
        } else {
          emit(RestorePasswordFailure(response.message));
        }
      } 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();
  }

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

    return super.close();
  }
}
