<script setup>
const props = defineProps({
  type: {
    required: true,
    type: String
  },
  items: {
    required: true,
    type: Array
  }
})

const {type} = props

defineShortcuts({
  '/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },
  '+': () => {
    router.push(`/${type}/create`)
  },
  'Enter': {
    usingInput: true,
    handler: () => {
      router.push(`/${type}/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 router = useRouter()
const dataStore = useDataStore()
const profileStore = useProfileStore()

const dataType = dataStore.dataTypes[type]

//Old

const selectedItem = ref(0)


const selectedColumns = ref(dataType.templateColumns.filter(i => !i.disabledInTable))
const columns = computed(() => dataType.templateColumns.filter((column) => !column.disabledInTable && selectedColumns.value.includes(column)))

const searchString = ref('')

const selectableFilters = ref(dataType.filters.map(i => i.name))
const selectedFilters = ref(dataType.filters.filter(i => i.default).map(i => i.name) || [])

const filteredRows = computed(() => {

  let tempItems = props.items

  if(selectedFilters.value.length > 0) {
    selectedFilters.value.forEach(filterName => {
      let filter = dataType.filters.find(i => i.name === filterName)
      tempItems = tempItems.filter(filter.filterFunction)
    })
  }

  if(!useRole().generalAvailableRights.value[type].showToAllUsers) {
    if(useRole().checkRight(`${type}-viewAll`)){
      console.log("Right to Show All")
    } else if(useRole().checkRight(type)){
      console.log("Only Righty to show Own")
      console.log(tempItems)
      tempItems = tempItems.filter(item => item.profiles.includes(profileStore.activeProfile.id))
    } else {
      console.log("No Right to Show")
      tempItems = []
    }
  }





  return useSearch(searchString.value, tempItems)
})
</script>

<template>
  <UDashboardNavbar :title="dataType.label" :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 v-if="useRole().checkRight(`${type}-create`)" @click="router.push(`/standardEntity/${type}/create`)">+ {{dataType.labelSingle}}</UButton>
    </template>
  </UDashboardNavbar>

  <UDashboardToolbar>
    <template #left v-if="$slots['left-toolbar']">
      <slot name="left-toolbar"/>
    </template>

    <template #right>
      <USelectMenu
          v-model="selectedColumns"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="dataType.templateColumns.filter(i => !i.disabledInTable)"
          multiple
          class="hidden lg:block"
          by="key"
          :color="selectedColumns.length !== dataType.templateColumns.filter(i => !i.disabledInTable).length ? 'primary' : 'white'"
          :ui-menu="{ width: 'min-w-max' }"
      >
        <template #label>
          Spalten
        </template>
      </USelectMenu>
      <USelectMenu
          v-if="selectableFilters.length > 0"
          icon="i-heroicons-adjustments-horizontal-solid"
          multiple
          v-model="selectedFilters"
          :options="selectableFilters"
          :color="selectedFilters.length > 0 ? 'primary' : 'white'"
          :ui-menu="{ width: 'min-w-max' }"
      >
        <template #label>
          Filter
        </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(`/standardEntity/${type}/show/${i.id}`) "
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: `Keine ${dataType.label} anzuzeigen` }"
  >
    <template
        v-for="column in dataType.templateColumns.filter(i => !i.disabledInTable)"
        v-slot:[`${column.key}-header`]="{row}">
      <span class="text-nowrap">{{column.label}}</span>
    </template>
    <template #name-data="{row}">
      <span
          v-if="row.id === filteredRows[selectedItem].id"
          class="text-primary-500 font-bold">{{row.name}}
      </span>
      <span v-else>
        {{row.name}}
      </span>
    </template>
    <template #fullName-data="{row}">
      <span
          v-if="row.id === filteredRows[selectedItem].id"
          class="text-primary-500 font-bold">{{row.fullName}}
      </span>
      <span v-else>
        {{row.fullName}}
      </span>
    </template>
    <template #licensePlate-data="{row}">
      <span
          v-if="row.id === filteredRows[selectedItem].id"
          class="text-primary-500 font-bold">{{row.licensePlate}}
      </span>
      <span v-else>
        {{row.licensePlate}}
      </span>
    </template>
    <template
        v-for="column in dataType.templateColumns.filter(i => i.key !== 'name' && i.key !== 'fullName' && i.key !== 'licensePlate' && !i.disabledInTable)"
        v-slot:[`${column.key}-data`]="{row}">
      <component v-if="column.component" :is="column.component" :row="row"></component>
      <span v-else>{{row[column.key] ? `${row[column.key]} ${column.unit ? column.unit : ''}`: ''}}</span>
    </template>
  </UTable>
</template>

<style scoped>

</style>