<template>
  <Toolbar>
    <UButton @click="router.push(`/services/create/`)">+ Leistung</UButton>

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


  <div class="table">
    <UTable
        :rows="filteredRows"
        :columns="itemColumns"
        @select="selectItem"
        :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Noch keine Einträge' }"
    >
      <template #sellingPrice-data="{row}">
        {{row.sellingPrice ? Number(row.sellingPrice).toFixed(2) + " €" : ""}}
      </template>
<!--      <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}">
        {{dataStore.units.find(unit => unit.id === row.unit) ? dataStore.units.find(unit => unit.id === row.unit).name : row.unit}}
      </template>
    </UTable>
  </div>

</template>

<script setup>

definePageMeta({
  middleware: "auth"
})
const dataStore = useDataStore()
const supabase = useSupabaseClient()
const router = useRouter()

const itemColumns = [
  {
    key: "name",
    label: "Name",
    sortable: true
  },
  {
    key: "unit",
    label: "Einheit",
    sortable: true
  },
  {
    key: "sellingPrice",
    label: "Verkaufspreis",
    sortable: true
  }/*,
  {
    key: "tags",
    label: "Tags",
    sortable: true
  }*/
]

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

const searchString = ref('')

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

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


</script>

<style scoped>

</style>