import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_request.dart';
import '../../base/restful_api_viewmodel.dart';
import '../../configs/constants.dart';
import '../../preference/data_preference.dart';
import '../create_pass/change_pass_repository.dart';
import '../create_pass/create_pass_screen.dart';
import '../login/login_viewmodel.dart';
import '../otp/forgot_pass_otp_repository.dart';
import '../otp/otp_screen.dart';

class ChangePassViewModel extends RestfulApiViewModel {
  var isPasswordVisible = false.obs;
  var password = "".obs;
  var loginState = LoginState.idle.obs;
  void Function(String message)? onShowAlertError;

  void onPasswordChanged(String value) {
    password.value = value;
    if (value.isEmpty) {
      loginState.value = LoginState.idle;
    } else {
      loginState.value = LoginState.typing;
    }
  }

  void togglePasswordVisibility() {
    isPasswordVisible.value = !isPasswordVisible.value;
  }

  void onForgotPassPressed(String phone) {
    showLoading();
    client.otpCreateNew(phone).then((value) {
      hideLoading();
      // TODO: handle error later
      if (value.isSuccess) {
        Get.to(OtpScreen(repository: ForgotPassOTPRepository(phone, value.data?.resendAfterSecond ?? Constants.otpTtl)));
      }
    });
  }

  Future<void> accountCheckForPasswordChange() async {
    showLoading();
    final phone = await DataPreference.instance.phone ?? "";
    client.accountLoginForPasswordChange(phone, password.value).then((value) {
      hideLoading();
      if (value.isSuccess) {
        Get.to(CreatePasswordScreen(repository: ChangePasswordRepository(phone)));
      } else {
        onShowAlertError?.call(value.errorMessage ?? Constants.commonError);
      }
    });
  }
}
