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

import '../../../../Api_Helper/base_manager.dart';
import '../../../../core/utils/secure/secure_storage_service.dart';
import '../../domain/repository/forgot_password_api.dart';
import 'restore_password_phone_verification_event.dart';
import 'restore_password_phone_verification_state.dart';

class RestorePasswordPhoneVerificationBloc extends Bloc<
    RestorePasswordPhoneVerificationEvent,
    RestorePasswordPhoneVerificationState> {
  final SharedPreferenceLocalData secureStorageService;
  String isdcode = "";

  String countryId = "";
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController phoneNumberTextField = TextEditingController();
  final TextEditingController countrySelectionTextField =
      TextEditingController();

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

  RestorePasswordPhoneVerificationBloc({required this.secureStorageService})
      : super(RestorePasswordPhoneVerificationInitial()) {
    phoneNumberTextField.addListener(_onFormFieldChanged);
    countrySelectionTextField.addListener(_onFormFieldChanged);
    on<RestorePasswordPhoneVerificationFormChanged>(_onLoginFormChanged);
    on<RestorePasswordPhoneVerificationSubmitted>((event, emit) async {
      emit(RestorePasswordPhoneVerificationLoading());
      try {
        Map<String, dynamic> dataForm = {
          "ISDcode": event.countryISDCode,
          "mobileNumber": event.phoneNumber
        };
        ResponseData response =
            await ForgotPasswordApi().forgotPasswordApi(dataForm);

        if (response.status == ResponseStatus.SUCCESS) {
          var data = response.data["data"];
          await secureStorageService.write('temp_token', data);
          Globalconst.token = data;
          emit(RestorePasswordPhoneVerificationSuccess());
        } else {
          emit(RestorePasswordPhoneVerificationFailure(response.message));
        }
      } catch (e) {
        emit(RestorePasswordPhoneVerificationFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(RestorePasswordPhoneVerificationFormChanged(
      phoneNumberTextField.text,
      countrySelectionTextField.text,
    ));
  }

  void _onLoginFormChanged(RestorePasswordPhoneVerificationFormChanged event,
      Emitter<RestorePasswordPhoneVerificationState> emit) {
    final areFieldsFilled =
        event.phoneNumber.isNotEmpty && event.country.isNotEmpty;
    emit(RestorePasswordPhoneVerificationFieldsState(areFieldsFilled));
  }

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

  @override
  Future<void> close() {
    phoneNumberTextField.dispose();
    countrySelectionTextField.dispose();

    return super.close();
  }
}
