import 'package:get/get.dart';
import 'package:mypoint_flutter_app/screen/create_pass/signup_create_password_repository.dart';

class CreatePasswordViewModel extends GetxController {
  final ICreatePasswordRepository repository;
  var newPassword = "".obs;
  var confirmPassword = "".obs;
  var errorMessage = "".obs;
  var isButtonEnabled = false.obs;

  CreatePasswordViewModel(this.repository);

  void onNewPasswordChanged(String value) {
    newPassword.value = value.trim();
    _validate();
  }

  void onConfirmPasswordChanged(String value) {
    confirmPassword.value = value.trim();
    _validate();
  }

  void _validate() {
    if (newPassword.value.isEmpty || confirmPassword.value.isEmpty) {
      errorMessage.value = "";
      isButtonEnabled.value = false;
      return;
    }
    if (newPassword.value != confirmPassword.value) {
      errorMessage.value = "Mật khẩu không khớp. Vui lòng kiểm tra.";
      isButtonEnabled.value = false;
    } else {
      errorMessage.value = "";
      isButtonEnabled.value = true;
    }
  }

  Future<void> onSubmit() async {
    if (!isButtonEnabled.value) return;
    try {
      final response = await repository.setPassword(newPassword.value);
      if (response.isSuccess) {
        errorMessage.value = "";
      } else {
        errorMessage.value = response.errorMessage ?? "Tạo mật khẩu thất bại. Thử lại sau.";
      }
    } catch (e) {
      errorMessage.value = "Có lỗi xảy ra: $e";
    }
  }
}
