<template>
  <div>

    <div class="flex items-center gap-1">
      <UButton @click="router.push(`/products/create/`)">+ Artikel</UButton>

      <UInput
          v-model="searchString"
          placeholder="Suche..."
      />
    </div>



    <UTable
      :rows="filteredRows"
      :columns="itemColumns"
      @select="selectItem"
    >
      <template #tags-data="{row}">
        <UBadge
            v-if="row.tags.length > 0"
          v-for="tag in row.tags"
          class="mr-2"
        >
          {{tag}}
        </UBadge>
        <span v-else>-</span>
      </template>
      <template #unit-data="{row}">
        {{units.find(unit => unit.id === row.unit) ? units.find(unit => unit.id === row.unit).name : row.unit}}
      </template>
    </UTable>


  </div>
</template>

<script setup>

definePageMeta({
  middleware: "auth"
})

const supabase = useSupabaseClient()
const router = useRouter()
const {products,units} = storeToRefs(useDataStore())

const itemColumns = [
  {
    key: "id",
    label: "Id"
  },
  {
    key: "name",
    label: "Name"
  },
  {
    key: "manufacturer",
    label: "Hersteller",
  },
  {
    key: "unit",
    label: "Einheit"
  },
  {
    key: "tags",
    label: "Tags"
  }
]

const selectItem = (item) => {
  console.log(item)
  router.push(`/products/show/${item.id} `)
}

const searchString = ref('')

const filteredRows = computed(() => {
  if(!searchString.value) {
    return products.value
  }

  return products.value.filter(product => {
    return Object.values(product).some((value) => {
      return String(value).toLowerCase().includes(searchString.value.toLowerCase())
    })
  })
})


</script>

<style scoped>

</style>