<script setup>
import dayjs from "dayjs";
const profileStore = useProfileStore()
const router = useRouter()

const tickets = ref([])
const tenants = ref([])

const showClosedTickets = ref(false)
const selectedTenant = ref(null)

const setup = async () => {
  tickets.value = await useEntities("tickets").select("*,created_by(*), ticketmessages(*)", "created_at", false)



}

setup()

const filteredRows = computed(() => {
  let items = tickets.value

  if(!showClosedTickets.value) {
    items = items.filter(i => i.status !== "Geschlossen")
  }

  if(selectedTenant.value) {
    console.log(selectedTenant.value)
    console.log(items)
    console.log(items.filter(i => i.tenant.id === selectedTenant.value))
    items = items.filter(i => i.tenant.id === selectedTenant.value)
  }

  return items

})

</script>

<template>
  <UDashboardNavbar
    title="Support Tickets"
    :badge="filteredRows.length"
  >
    <template #right>
      <UButton
        @click="router.push('/support/create')"
      >
        + Ticket
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <UCheckbox
        label="Geschlossene Tickets anzeigen"
        v-model="showClosedTickets"
      />
      <USelectMenu
          v-if="profileStore.currentTenant === 5"
        :content="{ width: 'min-w-max' }"
        :items="tenants"
        label-key="name"
        value-key="id"
        v-model="selectedTenant"
      >
        <template #default>
          {{selectedTenant ? tenants.find(i => i.id === selectedTenant).name : "Nicht nach Tenant filtern"}}
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>
  <UTable
    :data="filteredRows"
    :empty="{ icon: 'i-heroicons-circle-stack-20-solid', label: `Keine Tickets anzuzeigen` }"
    :on-select="(i) => router.push(`/support/${i.id}`)"
    :columns="normalizeTableColumns([{key:'created_at',label:'Datum'}, ...profileStore.currentTenant === 5 ? [{key:'tenant',label:'Tenant'}] : [],{key:'status',label:'Status'},{key:'title',label:'Titel'},{key:'created_by',label:'Ersteller'},{key:'ticketmessages',label:'Nachrichten'}])"
  >
    <template #tenant-cell="{ row }">
     {{row.original.tenant.name}}
    </template>
    <template #status-cell="{ row }">
     <span v-if="row.original.status === 'Offen'" class="text-yellow-500">Offen</span>
     <span v-else-if="row.original.status === 'Geschlossen'" class="text-primary">Geschlossen</span>
    </template>
    <template #created_by-cell="{ row }">
     {{row.original.created_by.fullName}}
    </template>
    <template #created_at-cell="{ row }">
     {{dayjs(row.original.created_at).format('DD.MM.YYYY HH:mm')}}
    </template>
    <template #ticketmessages-cell="{ row }">
     {{row.original.ticketmessages.length}}
    </template>
  </UTable>
</template>

<style scoped>

</style>
