<template>
  <UDashboardNavbar title="Inventar" :badge="filteredRows.length">
    <template #right>
      <UInput
          id="searchinput"
          v-model="searchString"
          icon="i-heroicons-funnel"
          autocomplete="off"
          placeholder="Suche..."
          class="hidden lg:block"
          @keydown.esc="$event.target.blur()"
      >
        <template #trailing>
          <UKbd value="/" />
        </template>
      </UInput>

      <UButton @click="router.push(`/inventoryitems/create`)">+ Inventarartikel</UButton>
    </template>
  </UDashboardNavbar>

  <UDashboardToolbar>
    <template #right>
      <USelectMenu
          v-model="selectedColumns"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="templateColumns"
          multiple
          class="hidden lg:block"
          by="key"
      >
        <template #label>
          Spalten
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>

  <UTable
      :rows="filteredRows"
      :columns="columns"
      class="w-full"
      :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
      @select="(i) => router.push(`/inventoryitems/show/${i.id}`) "
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Inventarartikel anzuzeigen' }"
      v-model:sort="sortConfig"
      sort-mode="manual"
      @update:sort="setupPage"
  >


  </UTable>
</template>

<script setup>
import {sort} from "fast-sort"


definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  '/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },
  '+': () => {
    router.push("/tasks/create")
  }
})

const dataStore = useDataStore()
const router = useRouter()
const items = ref([])

const sortConfig = ref({
  column: "articleNumber",
  direction: "desc"
})

const setupPage = async () => {
  items.value = await useSupabaseSelect("inventoryitems","*")
}

setupPage()

const templateColumns = [
  {
    key: "articleNumber",
    label: "Artikelnummer",
    sortable: true
  },{
    key: "name",
    label: "Name",
    sortable: true
  },
  {
    key: "description",
    label: "Beschreibung",
    sortable: true
  }
]
const selectedColumns = ref(templateColumns)
const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.includes(column)))



const searchString = ref('')
const filteredRows = computed(() => {

  let sorted = []

  if(sortConfig.value.direction === "asc"){
    sorted = sort(items.value).asc(i => i[sortConfig.value.column])
  } else {
    sorted = sort(items.value).desc(i => i[sortConfig.value.column])
  }

  return useListFilter(searchString.value, sorted)

})


</script>

<style scoped>

</style>