<template>
  <div class="full-height window-width row justify-center items-center">
    <q-infinite-scroll @load="onLoad" :offset="250">
      <div v-for="(lista, index) in store.listas" :key="index" class="caption">
        <div class="q-pa-md row items-start q-gutter-md">
          <q-card class="my-card text-white"
            :class="store.user?.email === lista.email_owner ? 'bg-secondary' : 'bg-green-7'">
            <q-card-section>
              <q-badge color="orange" class="text-subtitle2" floating trasparent>
                {{ lista.items ? lista.items.filter(i => !i.is_done).length : '0' }}/{{ lista.items ?
                  lista.items?.length : '0' }}
              </q-badge>
              <div class="text-h5">{{ lista.nombre }}
                <q-icon name="edit" @click="openDialogChangeNameList(lista.id)" class="cursor-pointer" />
              </div>
              <div class="text-subtitle1">{{ lista.email_owner }}</div>
            </q-card-section>

            <q-card-section>
              Compartido con:
              <span v-if="!lista.profiles || lista.profiles.length === 0">Nadie</span>
              <span v-for="(profile, index) in lista.profiles" :key="index">
                <br>- {{ profile.email }} <q-icon name="delete" @click="console.log(profile.email)"
                  class="cursor-pointer" />
              </span>
            </q-card-section>

            <q-separator dark />

            <q-card-actions>
              <q-btn flat>Editar</q-btn>
              <q-btn flat>Compartir</q-btn>
              <q-space></q-space>
              <q-btn class="bg-negative q-mr-md" flat>Borrar</q-btn>
            </q-card-actions>
          </q-card>
        </div>
      </div>
      <template v-slot:loading>
        <div class="row justify-center q-my-md">
          <q-spinner-dots color="primary" size="40px" />
        </div>
      </template>
    </q-infinite-scroll>
  </div>
  <q-dialog v-model="dialogChangeNameList" persistent enterConfirm>
    <q-card style="min-width: 350px">
      <q-card-section>
        <div class="text-h6">Nuevo nombre</div>
      </q-card-section>

      <q-card-section class="q-pt-none">
        <q-input dense v-model="newNameList" autofocus
          @keyup.enter="changeNameList(lista_id); dialogChangeNameList = false" />
      </q-card-section>

      <q-card-actions align="right" class="text-primary">
        <q-btn flat label="Cancel" v-close-popup />
        <q-btn flat label="Crear" v-close-popup @click="changeNameList(lista_id)" :disable="newNameList.length < 4" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import useSupabase from '../boot/supabase'
import { useQuasar } from 'quasar'
import { ref, onMounted } from 'vue'
import { supabaseStore } from '../stores/supabaseStore'

const { supabase } = useSupabase()
const $q = useQuasar()
const store = supabaseStore()

const dialogChangeNameList = ref(false)
const newNameList = ref('')
const lista_id = ref(0)

const ordenarArray = (array) => {
  array.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
}
const getListas = async () => {
  try {
    let { data: listas, error } = await supabase
      .from('listas')
      .select(`*, profiles(*),items(is_done)`)
    if (error) throw error
    console.log('listas', listas)
    store.listas = listas
    ordenarArray(store.listas)
  } catch (error) {
    if (error instanceof Error) {
      $q.notify({
        type: 'negative',
        message: error.message
      })
    }
  }
}

const onLoad = (index, done) => {
  setTimeout(() => {
    store.listas.push()
    done()
  }, 1000)
}

const changeNameList = async (id) => {
  try {
    const ahora = new Date()
    const { error } = await supabase
      .from('listas')
      .update({ nombre: newNameList.value, updated_at: ahora })
      .eq('id', id)
      .select()
    if (error) throw error
    store.listas.filter(l => l.id === id)[0].nombre = newNameList.value
    store.listas.filter(l => l.id === id)[0].updated_at = ahora
    ordenarArray(store.listas)
  } catch (error) {
    if (error instanceof Error) {
      $q.notify({
        type: 'negative',
        message: error.message
      })
    }
  }
}

const openDialogChangeNameList = (id) => {
  dialogChangeNameList.value = true
  lista_id.value = id
  newNameList.value = ''
}

onMounted(() => {
  getListas()
})
</script>
