<template>
  <div id="main">
    <!-- TODO: Kontakte erstellen und dem Kunden zuweisen    -->

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

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



    <UTable
        :rows="filteredRows"
        :columns="itemColumns"
        @select="selectItem"

    >
      <template #customer-data="{row}">
        {{customers.find(customer => customer.id === row.customer) ? customers.find(customer => customer.id === row.customer).name : row.customer }}
      </template>
    </UTable>

  </div>
</template>

<script setup>

definePageMeta({
  middleware: "auth"
})


const router = useRouter()
const {contracts, customers } = storeToRefs(useDataStore())
const mode = ref("show")

const itemColumns = [
  {
    key: 'customer',
    label: "Kundennr.:",
    sortable: true
  },
  {
    key: "name",
    label: "Name",
    sortable: true
  },
  {
    key: "description",
    label: "Beschreibung"
  }
]


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


const searchString = ref('')

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

  return contracts.value.filter(item => {
    return Object.values(item).some((value) => {
      return String(value).toLowerCase().includes(searchString.value.toLowerCase())
    })
  })
})
</script>

<style scoped>

</style>