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

import '../../../app.dart';

class OTPController extends GetxController {
  final String phone;

  OTPController({required this.phone});

  RxBool isLoading = false.obs;
  RxBool isValidOtp = true.obs;

  final formKey = GlobalKey<FormState>();
  TextEditingController passwordCtrl = new TextEditingController();

  RxString otpCode = ''.obs;

  void onOTPChange(String value) {
    otpCode.value = value;
  }

  Future<void> onConfirmButtonTapped() async {
    debugPrint('OTP: ${otpCode.value}');

    // 1. Check otp validation
    isValidOtp.value = otpCode.value.length == 4;

    if (!isValidOtp.value) {
      return;
    }

    // 2. Check form validation
    if (!formKey.currentState!.validate()) {
      return;
    }

    isLoading.value = true;

    final Map<String, dynamic> params = {
      'phone': phone,
      'token': otpCode.value, // auth sms code
      'password': passwordCtrl.text,
    };

    final result = await AuthApi.updatePassword(params);
    if (result) {
      Get.back();
      showSnack('success'.tr, 'password_updated'.tr);
    } else
      showSnack('error'.tr, 'error_occurred'.tr, SnackType.ERROR);

    isLoading.value = false;
  }
}
