<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="changeNameList(lista.id, lista.nombre)" class="cursor-pointer"
                  v-if="store.user?.email === lista.email_owner" />
              </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="unShareUser(profile.id, lista.id, profile.email)" class="cursor-pointer"
                  v-if="store.user?.email === lista.email_owner" />
              </span>
            </q-card-section>

            <q-separator dark />

            <q-card-actions>
              <q-btn flat>Editar</q-btn>
              <q-btn flat @click="shareUser(lista.id)">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>
</template>

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

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

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
    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, nombre) => {
  try {
    $q.dialog({
      title: 'Escriba',
      message: 'Nuevo nombre de la lista',
      html: true,
      prompt: {
        model: nombre,
        isValid: val => val.length > 4, // << here is the magic
        type: 'text'
      },
      ok: {
        push: true,

      },
      cancel: {
        push: true,
      },
      persistent: true
    }).onOk(async (data) => {
      const ahora = new Date()
      const { error } = await supabase
        .from('listas')
        .update({ nombre: data, updated_at: ahora })
        .eq('id', id)
        .select()
      if (error) {
        $q.notify({
          type: 'negative',
          message: error.message
        })
        throw error
      }
      store.listas.filter(l => l.id === id)[0].nombre = data
      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 unShareUser = async (user_id, lista_id, email) => {
  try {
    $q.dialog({
      title: 'Confirm',
      message: 'Está seguro que quiere dejar de compartir esta lista con <span class="text-negative">' + email + '</span>?',
      html: true,
      ok: {
        push: true,
        color: 'negative'
      },
      cancel: {
        push: true,
        color: 'positive'
      },
      persistent: true
    }).onOk(async () => {
      const { error } = await supabase
        .from('share')
        .delete()
        .eq('user_id', user_id)
        .eq('lista_id', lista_id)
      if (error) {
        $q.notify({
          type: 'negative',
          message: error.message
        })
        throw error
      }
      store.listas.filter(l => l.id === lista_id)[0].profiles = store.listas.filter(l => l.id === lista_id)[0].profiles.filter(p => p.id !== user_id)
    })

  } catch (error) {
    if (error instanceof Error) {
      $q.notify({
        type: 'negative',
        message: error.message
      })
    }
  }
}

const getProfileByEmail = async (email) => {
  try {
    const { data, error } = await supabase
      .from('profiles')
      .select()
      .eq('email', email.trim())
    if (error) throw error
    return data[0]
  } catch (error) {
    if (error instanceof Error) {
      $q.notify({
        type: 'negative',
        message: error.message
      })
    }
  }
}
const shareUser = async (id) => {
  $q.dialog({
    title: 'Escriba',
    message: 'Email del usuario',
    html: true,
    prompt: {
      model: '',
      isValid: val => val.length > 5, // << here is the magic
      type: 'text'
    },
    ok: {
      push: true,

    },
    cancel: {
      push: true,
    },
    persistent: true
  }).onOk(async (email) => {
    try {
      const profile = await getProfileByEmail(email)
      if (profile.email === store.user.email) {
        $q.notify({
          type: 'negative',
          message: 'No puede compartir la lista con usted mismo'
        })
        return
      }
      const { error } = await supabase
        .from('share')
        .insert([
          { user_id: profile.id, lista_id: id },
        ])
        .select()
      if (error) throw error
      store.listas.filter(l => l.id === id)[0].profiles.push(profile)
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('profile is undefined')) {
          $q.notify({
            type: 'negative',
            message: 'El email no existe en la base de datos'
          })
        } else {
          $q.notify({
            type: 'negative',
            message: error.message
          })
        }
      }
    }
  })
}

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