import 'package:get/get.dart';
import 'package:mypoint_flutter_app/features/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;
  var isSixDigits = false.obs;
  var isNotRepeatedSequence = false.obs;
  var isNotSequential = 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() {
    isSixDigits.value = _isSixDigits(newPassword.value);
    isNotRepeatedSequence.value = _isNotAllSameDigits(newPassword.value);
    isNotSequential.value = _isNotSequentialDigits(newPassword.value);

    if (!isSixDigits.value || !isNotRepeatedSequence.value || !isNotSequential.value) {
      errorMessage.value = "";
      isButtonEnabled.value = false;
      return;
    }
    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;
    }
  }

  bool _isSixDigits(String value) => RegExp(r'^\d{6}$').hasMatch(value);

  bool _isNotAllSameDigits(String value) {
    if (!_isSixDigits(value)) return false;
    final first = value[0];
    for (var i = 1; i < value.length; i++) {
      if (value[i] != first) return true;
    }
    return false;
  }

  bool _isNotSequentialDigits(String value) {
    if (!_isSixDigits(value)) return false;
    final digits = value.codeUnits.map((c) => c - 48).toList();
    var asc = true;
    var desc = true;
    for (var i = 1; i < digits.length; i++) {
      if (digits[i] != digits[i - 1] + 1) asc = false;
      if (digits[i] != digits[i - 1] - 1) desc = false;
    }
    return !(asc || desc);
  }

  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";
    }
  }
}
