<template>
  <q-card-section class="q-ma-sm">
    <q-input
      v-model="password"
      label="New Password"
      type="password"
      color="darkblue"
      :rules="[validatePasswordStrength]"
      lazy-rules
      filled></q-input>
    <q-input
      v-model="confirmPassword"
      label="Confirm New Password"
      type="password"
      color="darkblue"
      :rules="[validatePasswordStrength]"
      lazy-rules
      filled></q-input>
    <div class="text-caption q-py-md">Enter a new password.</div>
  </q-card-section>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

const password = ref('');
const confirmPassword = ref('');

const newPassword = defineModel();

const validatePasswordStrength = (val: string) => {
  const hasUpperCase = /[A-Z]/.test(val);
  const hasLowerCase = /[a-z]/.test(val);
  const hasNumbers = /[0-9]/.test(val);
  const hasNonAlphas = /[\W_]/.test(val);
  const isValidLength = val.length >= 8;

  return (
    (hasUpperCase &&
      hasLowerCase &&
      hasNumbers &&
      hasNonAlphas &&
      isValidLength) ||
    'Password must be at least 8 characters long and include uppercase, lowercase, number, and special character.'
  );
};

const validatePasswordsMatch = (val: string) => {
  return val === password.value || 'Passwords do not match.';
};

watch([password, confirmPassword], ([newpw, newpw1]) => {
  if (
    validatePasswordStrength(newpw) === true &&
    validatePasswordsMatch(newpw1) === true
  ) {
    newPassword.value = newpw;
  } else {
    newPassword.value = '';
  }
});
</script>
