<template>
  <UDashboardNavbar title="Projekte" :badge="filteredRows.length">
    <template #right>
      <UInput
          id="searchinput"
          v-model="searchString"
          icon="i-heroicons-funnel"
          autocomplete="off"
          placeholder="Suche..."
          class="hidden lg:block"
          @keydown.esc="$event.target.blur()"
      >
        <template #trailing>
          <UKbd value="/" />
        </template>
      </UInput>

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

  <UDashboardToolbar>
    <template #left>


      <UCheckbox
          label="Abgeschlossene anzeigen"
          v-model="showFinished"
          class="mt-1"
      />
      <USelectMenu
          class="ml-3 w-36"
        v-model="selectedTypes"
        :options="projecttypes"
        value-attribute="id"
        option-attribute="name"
        multiple
      >
        <template #label>
          Typen
        </template>
      </USelectMenu>
    </template>

    <template #right>
      <USelectMenu
          v-model="selectedColumns"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="templateColumns"
          multiple
          class="hidden lg:block"
          by="key"
      >
        <template #label>
          Spalten
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>




  <UTable
      :rows="filteredRows"
      :columns="columns"
      class="w-full"
      :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
      @select="(i) => router.push(`/projects/show/${i.id}`) "
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Projekte anzuzeigen' }"
  >
    <template #name-data="{row}">
      <span class="text-primary-500 font-bold" v-if="row === filteredRows[selectedItem]">{{row.name}}</span>
      <span v-else>{{row.name}}</span>
    </template>
    <template #projecttype-data="{row}">
      {{row.projecttype ? row.projecttype.name : ""}}
    </template>
    <template #phase-data="{row}">
      {{getActivePhaseLabel(row)}}
    </template>
    <template #customer-data="{row}">
      {{row.customer ? row.customer.name : ""}}
    </template>
    <template #plant-data="{row}">
      {{row.plant ? row.plant.name : ""}}
    </template>
    <template #users-data="{row}">
      {{row.users.map(i => dataStore.getProfileById(i).fullName).join(", ")}}
    </template>
  </UTable>

</template>

<script setup>
definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  '/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },
  '+': () => {
    router.push("/projects/create")
  },
  'Enter': {
    usingInput: true,
    handler: () => {
      router.push(`/projects/show/${filteredRows.value[selectedItem.value].id}`)
    }
  },
  'arrowdown': () => {
    if(selectedItem.value < filteredRows.value.length - 1) {
      selectedItem.value += 1
    } else {
      selectedItem.value = 0
    }
  },
  'arrowup': () => {
    if(selectedItem.value === 0) {
      selectedItem.value = filteredRows.value.length - 1
    } else {
      selectedItem.value -= 1
    }
  }
})

const dataStore = useDataStore()
const router = useRouter()

const items = ref([])
const selectedItem = ref(0)
const projecttypes = ref([])
const selectedTypes = ref([])

const setupPage = async () => {
  items.value = await useSupabaseSelect("projects","*, customer (name), plant(name), projecttype(name, id)","projectNumber")
  projecttypes.value = await useSupabaseSelect("projecttypes","*")
  selectedTypes.value = projecttypes.value.map(i => i.id)
}

setupPage()

const templateColumns = [
  {
    key: "projectNumber",
    label: "Projektnummer"
  },
  {
    key: "projecttype",
    label: "Typ"
  },
  {
    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 selectedColumns = ref(templateColumns)
const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.includes(column)))


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 temp = items.value.map(item => {
    return  {
      ...item,
      phaseLabel: getActivePhaseLabel(item)
    }
  })

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

  temp = temp.filter(i => !i.projecttype || selectedTypes.value.includes(i.projecttype.id))

  if(!searchString.value) {
    return temp
  }
  return useSearch(searchString.value, temp)
})
</script>