<template>
  <InputGroup >
    <UButton @click="router.push(`/projects/create/`)">+ Projekt</UButton>

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

    <UCheckbox
      label="Abgeschlossene anzeigen"
      v-model="showFinished"
    />
  </InputGroup>


  <div class="table">
    <UTable
        :rows="filteredRows"
        @select="selectItem"
        :columns="itemColumns"
        :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Noch keine Einträge' }"
    >
      <template #phase-data="{row}">
        {{getActivePhaseLabel(row)}}
      </template>
      <template #customer-data="{row}">
        {{dataStore.getCustomerById(row.customer) ? dataStore.getCustomerById(row.customer).name : ""}}
      </template>
      <template #plant-data="{row}">
        {{dataStore.getPlantById(row.plant) ? dataStore.getPlantById(row.plant).name : ""}}
      </template>
      <template #users-data="{row}">
        {{row.users.map(i => dataStore.getProfileById(i).fullName).join(", ")}}
      </template>
    </UTable>
  </div>

</template>

<script setup>

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

const itemColumns = [
  {
    key: "phase",
    label: "Phase"
  },
  {
    key: "measure",
    label: "Gewerk"
  },{
    key: "name",
    label: "Name"
  },
  {
    key: "customer",
    label: "Kunde",
    sortable: true
  },/*
  {
    key: "notes",
    label: "Notizen",
    sortable: true
  },*/
  {
    key: "plant",
    label: "Objekt",
    sortable: true
  },
  {
    key: "users",
    label: "Benutzer",
    sortable: true
  }
]

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

const getActivePhaseLabel = (item) => {
  if(item.phases) {
    if(item.phases.length > 0) {

      let activePhase = item.phases.find(i => i.active)

      if(activePhase) {
        return activePhase.label
      } else {
        return  ""
      }
    }
  }
}


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

const filteredRows = computed(() => {
  let items = dataStore.projects

  items = items.map(item => {
    return  {
      ...item,
      phaseLabel: getActivePhaseLabel(item)
    }
  })

  if(showFinished.value) {
    items = items.filter(i => i.phaseLabel === "Abgeschlossen")
  } else {
    items = items.filter(i => i.phaseLabel !== "Abgeschlossen")
  }

  if(!searchString.value) {
    return items
  }



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


</script>

<style scoped>

</style>