import 'package:get/get.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import '../../core/network/restful_api_viewmodel.dart';
import '../../shared/router_gage.dart';
import '../otp/otp_screen.dart';
import '../otp/verify_otp_repository.dart';
import 'model/check_phone_response_model.dart';
import 'model/onboarding_info_model.dart';

class OnboardingViewModel extends RestfulApiViewModel {
  final RxString phoneNumber = "".obs;
  final RxBool isChecked = true.obs;
  final _info = Rxn<OnboardingInfoModel>();
  var checkPhoneRes = Rxn<CheckPhoneResponseModel>();
  void Function(String message)? onShowAlertError;
  bool get isButtonEnabled => isChecked.value && phoneNumber.value.isPhoneValid();
  String get content => _info.value?.content ?? "";
  String get url => _info.value?.url ?? "";

  void updatePhoneNumber(String value) {
    phoneNumber.value = value;
  }

  void toggleCheckbox(bool? value) {
    isChecked.value = value!;
  }

  Future<void> fetchOnboardingContent() async {
    await callApi<OnboardingInfoModel>(
      request: () => client.getOnboardingInfo(),
      onSuccess: (data, _) {
        _info.value = data;
      },
      withLoading: false,
    );
  }

  Future<void> checkPhoneNumber() async {
    await callApi<CheckPhoneResponseModel>(
      request: () => client.checkPhoneNumber(phoneNumber.value),
      onSuccess: (data, _) {
        checkPhoneRes.value = data;
        if (data.requireRecaptcha == true) return;
        final mfaToken = data.mfaToken ?? "";
        final nextAction = data.nextAction ?? "";
        final otpTtl = data.otpTtl ?? 0;
        if (mfaToken.isNotEmpty || (nextAction == "signup")) {
          Get.to(() => OtpScreen(repository: VerifyOtpRepository(phoneNumber.value, otpTtl, mfaToken)));
          return;
        }
        if (nextAction == "login") {
          Get.toNamed(loginScreen, arguments: {'phone': phoneNumber.value});
        }
      },
      onFailure: (msg, _, _) {
        onShowAlertError?.call(msg);
      },
    );
  }
}
