<template>
  <div id="main">

    <InputGroup>
      <UButton @click="router.push(`/tasks/create`)">+ Aufgabe</UButton>

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

      <UCheckbox
          label="Erledigte Anzeigen"
          v-model="showDone"
      />
    </InputGroup>

    <UTable
        :rows="filteredRows"
        :columns="columns"
        @select="selectItem"
        :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Noch keine Einträge' }"
    >
      <template #created_at-data="{row}">
        {{row.created_at ? dayjs(row.created_at).format("DD.MM.YY HH:mm") : ''}}
      </template>
      <template #user-data="{row}">
        {{dataStore.profiles.find(i => i.id === row.user) ? dataStore.profiles.find(i => i.id === row.user).fullName : ""}}
      </template>
      <template #project-data="{row}">
        {{dataStore.projects.find(i => i.id === row.project) ? dataStore.projects.find(i => i.id === row.project).name : ""}}
      </template>
      <template #customer-data="{row}">
        {{dataStore.customers.find(customer => customer.id === row.customer) ? dataStore.customers.find(customer => customer.id === row.customer).name : "" }}
      </template>
    </UTable>

  </div>
</template>

<script setup>
import * as dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const router = useRouter()
const mode = ref("show")

const columns = [
  {
    key: "created_at",
    label: "Erstellt am:",
    sortable: true
  },{
    key: "name",
    label: "Name:",
    sortable: true
  },{
    key: "categorie",
    label: "Kategorie:",
    sortable: true
  },{
    key: "description",
    label: "Beschreibung:",
    sortable: true
  },{
    key: "user",
    label: "Benutzer:",
    sortable: true
  },{
    key: "project",
    label: "Projekt:",
    sortable: true
  },{
    key: "plant",
    label: "Anlage:",
    sortable: true
  }
]

const searchString = ref('')
const showDone = ref(false)


const filteredRows = computed(() => {
  let tasks = dataStore.tasks

  if(!showDone.value) {
    tasks = tasks.filter(i => i.categorie !== "Erledigt")
  }

  if(!searchString.value) {
    return tasks
  }

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

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

<style scoped>

</style>