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

definePageMeta({
  middleware: "auth"
})

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

let currentItem = ref(null)

//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
    name: null,
    description: null,
  quantity: 0
})

//Functions
const setupPage = async () => {
  if(mode.value === "show" || mode.value === "edit"){
    currentItem.value = await useSupabaseSelectSingle("inventoryitems", route.params.id, "*, vendor(*)")
  }

  if(mode.value === "edit") itemInfo.value = currentItem.value
}

const cancelEditorCreate = () => {
  if(currentItem.value) {
    router.push(`/inventoryitems/show/${currentItem.value.id}`)
  } else {
    router.push(`/inventoryitems`)
  }
}

setupPage()
</script>

<template>
  <UDashboardNavbar :title="currentItem ? currentItem.name : (mode === 'create' ? 'Inventartikel erstellen' : 'Inventartikel bearbeiten')">
    <template #right>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('inventoryitems',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('inventoryitems',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="cancelEditorCreate"
          color="red"
          class="ml-2"
          v-if="mode === 'edit' || mode === 'create'"
      >
        Abbrechen
      </UButton>
      <UButton
          v-if="mode === 'show'"
          @click="  router.push(`/inventoryitems/edit/${currentItem.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UTabs
    :items="[{label: 'Informationen'}, {label: 'Logbuch'}]"
    v-if="currentItem && mode == 'show'"
    class="p-5"
  >
    <template #item="{item}">
      <UCard class="mt-5">
        <div v-if="item.label === 'Informationen'">

          <div class="text-wrap">
            <p v-if="currentItem.currentSpace">Lagerplatz: {{dataStore.getSpaceById(currentItem.currentSpace).spaceNumber}} - {{dataStore.getSpaceById(currentItem.currentSpace).description}}</p>
            <p>Seriennummer: {{currentItem.serialNumber}}</p>
            <p>Menge: {{currentItem.quantity > 0 ? currentItem.quantity : 'Einzelarktikel'}}</p>
            <p>Artikelnummer: {{currentItem.articleNumber}}</p>
            <p>Lieferant: {{currentItem.vendor ? currentItem.vendor.name : ''}}</p>
            <p>Kaufdatum: {{currentItem.purchaseDate}}</p>
            <p>Beschreibung: {{currentItem.description}}</p>
          </div>
        </div>
        <div v-else-if="item.label === 'Logbuch'">
          <HistoryDisplay
              type="inventoryitem"
              v-if="currentItem"
              :element-id="currentItem.id"
          />
        </div>
      </UCard>
    </template>
  </UTabs>
  <UForm
      v-else-if="mode == 'edit' || mode == 'create'"
      class="p-5"
  >
    <div class="flex flex-row">
      <div class="w-1/2 mr-5">
        <UDivider>
          Allgemeines
        </UDivider>
        <UFormGroup
          label="Name:"
        >
          <UInput
              v-model="itemInfo.name"
          />
        </UFormGroup>

        <UFormGroup
            label="Artikelnummer:"
        >
          <UInput
              v-model="itemInfo.articleNumber"
              placeholder="Leer lassen für automatische generierte Nummer"
          />
        </UFormGroup>
        <UFormGroup
            label="Lagerplatz:"
        >
          <USelectMenu
              :options="dataStore.spaces"
              v-model="itemInfo.currentSpace"
              value-attribute="id"
          >
            <template #option="{option}">
              <span class="truncate">{{option.spaceNumber}} - {{option.description}}</span>
            </template>
            <template #label>
              <span v-if="itemInfo.currentSpace">{{dataStore.getSpaceById(itemInfo.currentSpace).spaceNumber }} - {{dataStore.getSpaceById(itemInfo.currentSpace).description}}</span>
              <span v-else>Kein Lagerplatz ausgewählt</span>
            </template>
          </USelectMenu>
        </UFormGroup>
        <UFormGroup
            label="Seriennummer:"
        >
          <UInput
              v-model="itemInfo.serialNumber"
          />
        </UFormGroup>
        <UFormGroup
            label="Menge:"
            help="Für Einzelartikel Menge gleich 0"
        >
          <UInput
              type="number"
              v-model="itemInfo.quantity"
          />
        </UFormGroup>
      </div>
      <div class="w-1/2">
        <UDivider>
          Anschaffung
        </UDivider>
        <UFormGroup
            label="Hersteller:"
        >
          <UInput
              v-model="itemInfo.manufacturer"
          />
        </UFormGroup>
        <UFormGroup
            label="Herstellernr.:"
        >
          <UInput
              v-model="itemInfo.manufacturerNumber"
          />
        </UFormGroup>
        <UFormGroup
            label="Lieferant:"
        >
          <USelectMenu
              :options="dataStore.vendors"
              option-attribute="name"
              value-attribute="id"
              searchable
              :search-attributes="['name']"
              v-model="itemInfo.vendor"
          />
        </UFormGroup>
        <UFormGroup
            label="Kaufdatum:"
        >
          <UPopover :popper="{ placement: 'bottom-start' }">
            <UButton
                icon="i-heroicons-calendar-days-20-solid"
                :label="itemInfo.purchaseDate ? dayjs(itemInfo.purchaseDate).format('DD.MM.YYYY') : 'Datum auswählen'"
                variant="outline"
            />

            <template #panel="{ close }">
              <LazyDatePicker v-model="itemInfo.purchaseDate" @close="close" />
            </template>
          </UPopover>
        </UFormGroup>
        <UFormGroup
            label="Kaufpreis:"
        >
          <UInput
              v-model="itemInfo.purchasePrice"
              type="number"
              steps="0.01"
          >
            <template #trailing>
              <span class="text-gray-500 dark:text-gray-400 text-xs">EUR</span>
            </template>
          </UInput>
        </UFormGroup>
      </div>
    </div>


    <UFormGroup
        label="Beschreibung:"
    >
      <UTextarea
          v-model="itemInfo.description"
      />
    </UFormGroup>
  </UForm>
</template>

<style scoped>

</style>