<template>
  <div
    class="bg-light-green window-height window-width row justify-center items-center"
  >
    <div class="column">
      <div class="row">
        <h5 class="text-h5 text-white q-my-md">Mis listas</h5>
      </div>
      <div class="row">
        <q-card square bordered class="q-pa-lg shadow-1">
          <q-card-section>
            <q-form class="q-gutter-md" @click.once="recibeDatos()">
              <q-input
                square
                filled
                clearable
                v-model="username"
                type="text"
                label="username"
                :rules="[
                  (val) =>
                    (val != null && val.length >= 3) || 'Mínimo 3 caracteres',
                  (val) => comprobarUsername || 'Ya existe en la BD',
                  (val) => /^[A-Z0-9]+$/i.test(val) || 'Sólo letras o números',
                ]"
              />
              <q-input
                square
                filled
                clearable
                v-model="nombre"
                type="text"
                label="nombre completo"
                :rules="[
                  (val) =>
                    (val != null && val.length >= 3) || 'Mínimo 3 caracteres',
                ]"
              />
              <q-input
                square
                filled
                clearable
                v-model="email"
                type="email"
                label="email"
                :rules="[
                  (val) =>
                    (val != null && val.length >= 7) || 'Mínimo 7 caracteres',
                  (val) =>
                    comprobarEmail ||
                    'No es un email válido o ya existe en la BD',
                ]"
              />
              <q-input
                square
                filled
                clearable
                v-model="password"
                type="password"
                label="password"
                :rules="[
                  (val) =>
                    (val != null && val.trim().length >= 8) ||
                    'Mínimo 8 caracteres',
                ]"
              />
              <q-input
                square
                filled
                clearable
                v-model="confirmpassword"
                type="password"
                label="repite password"
                error-message="No coinciden"
                :error="comprobarConfirmPassword"
              />
            </q-form>
          </q-card-section>
          <q-card-actions class="q-px-md">
            <q-btn
              :disable="btnRegisterDisable()"
              unelevated
              color="light-green-7"
              size="lg"
              class="full-width"
              label="Register"
              @click="registrar()"
            />
          </q-card-actions>
          <q-card-section class="text-center q-pa-none">
            <p class="text-grey-6">
              <router-link to="/login"
                >Está registrado? Página de login</router-link
              >
            </p>
          </q-card-section>
        </q-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useListaStore } from "../stores/lista.js";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";

const listaStore = useListaStore();
const $q = useQuasar();
const $router = useRouter();

const email = ref("");
const password = ref("");
const username = ref("");
const confirmpassword = ref("");
const nombre = ref("");
const usuarios = ref([]);

const recibeDatos = () => {
  listaStore.getUsers().then(function (item) {
    usuarios.value = item;
  });
};

const comprobarUsername = computed(() => {
  let filtro = usuarios.value?.filter(
    (user) => user.username.toLowerCase() == username.value.trim().toLowerCase()
  );
  if (filtro.length == 0) {
    return true;
  }
  return false;
});

const comprobarEmail = computed(() => {
  const emailPattern =
    /^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,8}[a-zA-Z]{2,63}$/;
  let filtro = usuarios.value?.filter(
    (user) => user.email == email.value.trim()
  );
  if (emailPattern.test(email.value) && filtro.length == 0) {
    return true;
  }
  return false;
});

const comprobarConfirmPassword = computed(
  () => password.value != confirmpassword.value
);

const btnRegisterDisable = () => {
  if (
    username.value == null ||
    username.value.length < 3 ||
    !comprobarUsername.value ||
    !/^[A-Z0-9]+$/i.test(username.value) ||
    nombre.value == null ||
    nombre.value.length < 3 ||
    email.value == null ||
    email.value.length < 7 ||
    !comprobarEmail.value ||
    password.value == null ||
    password.value.trim().length < 8 ||
    confirmpassword.value == null ||
    comprobarConfirmPassword.value
  ) {
    return true;
  }
  return false;
};

const registrar = () => {
  const data = {
    username: username.value,
    email: email.value,
    emailVisibility: true,
    password: password.value,
    passwordConfirm: confirmpassword.value,
    name: nombre.value,
  };
  listaStore.register(data).then((r) => {
    $q.dialog({
      title: "Aviso",
      message: "Se le ha enviado un correo electrónico que debe verificar",
    }).onOk(() => {
      $router.push("/");
    });
  });
};
</script>

<style scoped>
a:link,
a:visited,
a:active {
  text-decoration: none;
  color: gray;
}
</style>
