<template>
  <div
    class="flex flex-center bg-teal-7 q-ma-md cursor-pointer"
    @click="irPerfil()"
  >
    <h1 style="font-weight: 415">
      {{ listaStore.pb.authStore.model.username }}
    </h1>
  </div>
  <div class="flex flex-center">
    <q-btn
      outline
      rounded
      color="primary"
      label="Nueva Lista"
      @click="crearLista()"
    />
  </div>
  <div class="flex flex-center q-pt-xl q-mt-xl">
    <div
      class="full-width text-center q-px-md"
      v-for="lista in listas"
      :key="lista.id"
    >
      <p class="bg-cyan-7 q-pa-md text-weight-bold text-h6">
        {{ lista.nombre
        }}<q-icon
          class="float-right cursor-pointer q-mt-xs"
          name="delete"
          @click="eliminarLista(lista)"
        />
      </p>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { useListaStore } from "../stores/lista.js";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";

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

const listas = ref(null);

const listListas = async () => {
  listas.value = await listaStore.pb.collection("lista").getFullList({
    sort: "-created",
  });
};

const irPerfil = () => {
  $router.push("perfil");
};

const crearLista = () => {
  $q.dialog({
    title: "Nueva lista",
    message: "Nombre de la lista",
    prompt: {
      model: "",
      isValid: (val) => val.length > 2,
      type: "text", // optional
    },
    cancel: true,
    persistent: true,
  })
    .onOk((nombreLista) => {
      console.log(">>>> OK, received", nombreLista);
      const data = {
        nombre: nombreLista.trim(),
        usuarios: [listaStore.pb.authStore.model.id],
        items: [],
      };
      listaStore.pb
        .collection("lista")
        .create(data)
        .then((r) => {
          console.log("creada");
          listListas();
        })
        .catch((e) => {
          console.log(e);
        });
    })
    .onCancel((e) => {
      console.log(e);
    });
};

const eliminarLista = (l) => {
  console.log(l.id);
  $q.dialog({
    title: l.nombre,
    message: "Está seguro de querer eliminar " + l.nombre + "?",
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    await listaStore.pb.collection("lista").delete(l.id);
    listListas();
  });
};
onMounted(() => {
  listListas();
});
</script>
