<script setup>
import HistoryDisplay from "~/components/HistoryDisplay.vue";



defineShortcuts({
  'backspace': () => {
    router.push("/roles")
  },
  'arrowleft': () => {
    const currentIndex = Number(openTab.value)
    if(currentIndex > 0){
      openTab.value = String(currentIndex - 1)
    }
  },
  'arrowright': () => {
    const currentIndex = Number(openTab.value)
    if(currentIndex < 3) {
      openTab.value = String(currentIndex + 1)
    }
  },
})

const dataStore = useDataStore()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const id = ref(route.params.id ? route.params.id : null )

const role = useRole()

//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
    rights: []
})
const openTab = ref("0")

//Functions
const setupPage = async () => {
  if(mode.value === "show" || mode.value === "edit"){
    itemInfo.value = await useEntities("roles").selectSingle(route.params.id,"*")
  }
}

const rightOptions = computed(() => {
  console.log(Object.keys(useRole().generalAvailableRights.value))
  return Object.keys(useRole().generalAvailableRights.value).map(i => {
    return {
      key: i,
      label: role.generalAvailableRights.value[i].label
    }
  })
})

const rightList = computed(() => {
  console.log(rightOptions.value)

  return itemInfo.value.rights.map(i => {
    if(rightOptions.value.find(x => x.key === i)) {
      return rightOptions.value.find(x => x.key === i).label
    } else {
      return i
    }
  }).join(", ")
})

setupPage()
</script>

<template>
  <UDashboardNavbar
      :ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
  >
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/roles`)"
      >
        Artikel
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          class="text-xl font-medium"
      >{{itemInfo.name ? `Rolle: ${itemInfo.name}` : (mode === 'create' ? 'Rolle erstellen' : 'Rolle bearbeiten')}}</h1>
    </template>
    <template #right>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('roles',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('roles',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="router.push(itemInfo.id ? `/roles/show/${itemInfo.value.id}` : `/products/`)"
          color="red"
          class="ml-2"
          v-if="mode === 'edit' || mode === 'create'"
      >
        Abbrechen
      </UButton>
      <UButton
          v-if="mode === 'show'"
          @click="  router.push(`/roles/edit/${itemInfo.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UTabs
    :items="[{label: 'Informationen'}]"
    v-if="mode === 'show' && itemInfo"
    class="p-5"
    v-model="openTab"
  >
    <template #content="{item}">
      <div v-if="item.label === 'Informationen'" class="mt-5 flex flex-row">
        <div class="w-1/2 mr-5">
          <UCard>
            <table class="w-full">
              <tr>
                <td>Name:</td>
                <td>{{itemInfo.name}}</td>
              </tr>
              <tr>
                <td>Rechte:</td>
                <td>{{rightList}}</td>
              </tr>
              <tr>
                <td>Beschreibung:</td>
                <td>{{itemInfo.description}}</td>
              </tr>
            </table>
          </UCard>
        </div>
        <div class="w-1/2">
          <UCard>
            <HistoryDisplay
                type="role"
                v-if="itemInfo"
                :element-id="id"
                render-headline
            />
          </UCard>
        </div>
      </div>
    </template>
  </UTabs>
  <UForm
      v-else-if="mode == 'edit' || mode == 'create'"
      class="p-5"
  >
    <UFormField
        label="Name:"
    >
      <UInput
          v-model="itemInfo.name"
          autofocus
      />
    </UFormField>
    <UFormField
        label="Rechte:"
    >
      <USelectMenu
          :options="rightOptions"
          value-attribute="key"
          option-attribute="label"
          v-model="itemInfo.rights"
          multiple
      >
      </USelectMenu>
    </UFormField>
    <UFormField
        label="Beschreibung:"
    >
      <UTextarea
          v-model="itemInfo.description"
      />
    </UFormField>
  </UForm>
</template>

<style scoped>
td {
  border-bottom: 1px solid lightgrey;
  vertical-align: top;
  padding-bottom: 0.15em;
  padding-top: 0.15em;
}
</style>
