<template>
  <div class="flex q-ma-md">
    <q-btn
      round
      color="deep-orange"
      icon="keyboard_return"
      @click="
        cargarDatos();
        $router.push('/');
      "
    />
  </div>
  <q-page class="flex flex-center">
    <div class="column q-gutter-sm">
      <div class="row flex-center q-pb-md q-mb-md">
        <q-avatar size="96px">
          <img
            :src="
              listaStore.pb.authStore.model.avatar.length > 0
                ? listaStore.pb.getFileUrl(
                    listaStore.pb.authStore.model,
                    listaStore.pb.authStore.model.avatar
                  )
                : `https://cdn.quasar.dev/img/avatar.png`
            "
          />
        </q-avatar>
      </div>
      <q-form class="q-gutter-md" @click.once="recibeDatos()">
        <div class="row" style="max-width: 198px">
          <q-file
            class="full-width q-mb-md"
            outlined
            v-model="imagen"
            label="Avatar"
          />
        </div>
        <div class="row">
          <q-input
            outlined
            v-model="name"
            label="Name"
            :rules="[
              (val) =>
                (val != null && val.length >= 3) || 'Mínimo 3 caracteres',
            ]"
          />
        </div>
        <div class="row">
          <q-input
            outlined
            v-model="username"
            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',
            ]"
          />
        </div>
        <div class="row">
          <q-input
            outlined
            v-model="listaStore.pb.authStore.model.email"
            label="email"
            disable
          />
        </div>
      </q-form>
      <div class="row q-mt-md q-mx-auto">
        <div class="col">
          <q-btn flat color="primary" label="Cancelar" @click="cargarDatos()" />
          <q-btn
            flat
            :disable="btnSaveDisable()"
            color="secondary"
            label="Guardar"
            @click="alertSave = true"
          />
        </div>
      </div>
      <q-dialog v-model="alertSave" persistent>
        <q-card>
          <q-card-section class="row items-center">
            <q-avatar icon="warning" color="warning" text-color="white" />
            <span class="q-ml-sm">Está seguro de guardar los datos?</span>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn
              flat
              label="No"
              color="negative"
              v-close-popup
              @click="cargarDatos()"
            />
            <q-btn
              flat
              label="Guardar"
              color="accent"
              v-close-popup
              @click="updateUser()"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
  </q-page>
</template>
<script setup>
import { ref, computed } from "vue";
import { useListaStore } from "../stores/lista.js";

const listaStore = useListaStore();

const imagen = ref(null);
const username = ref(listaStore.pb.authStore.model.username);
const name = ref(listaStore.pb.authStore.model.name);
const alertSave = ref(false);
const usuarios = ref([]);

const updateUser = async () => {
  const formData = new FormData();
  if (username.value.trim().length > 0) {
    formData.append("username", username.value.trim());
  }
  if (name.value.trim().length > 0) {
    formData.append("name", name.value.trim());
  }
  if (imagen.value != null) {
    formData.append("avatar", imagen.value);
  }
  await listaStore.pb
    .collection("users")
    .update(listaStore.pb.authStore.model.id, formData)
    .then((r) => {
      cargarDatos();
    });
  recibeDatos();
};
const cargarDatos = () => {
  imagen.value = null;
  username.value = listaStore.pb.authStore.model.username.trim();
  name.value = listaStore.pb.authStore.model.name.trim();
};

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;
  } else if (
    filtro.length == 1 &&
    filtro[0].username == listaStore.pb.authStore.model.username
  ) {
    return true;
  }
  return false;
});

const btnSaveDisable = () => {
  if (
    username.value == null ||
    username.value.length < 3 ||
    !comprobarUsername.value ||
    !/^[A-Z0-9]+$/i.test(username.value) ||
    name.value == null ||
    name.value.length < 3
  ) {
    return true;
  }
  return false;
};
</script>
