<script setup>
import HistoryDisplay from "~/components/HistoryDisplay.vue";
import dayjs from "dayjs";
import {useSupabaseSelectSingle} from "~/composables/useSupabase.js";

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 )

//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"){
    itemInfo.value = await useSupabaseSelectSingle("inventoryitems", route.params.id, "*, vendor(*)")
  } else if(mode.value === "edit") {
    itemInfo.value = await useSupabaseSelectSingle("inventoryitems", route.params.id, "*")
  }
}

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

setupPage()
</script>

<template>
  <UDashboardNavbar :title="itemInfo ? itemInfo.name : (mode === 'create' ? 'Inventartikel erstellen' : 'Inventartikel bearbeiten')">
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/inventoryitems`)"
      >
        Inventar
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          :class="['text-xl','font-medium']"
      >{{itemInfo.id ? `Inventarartikel: ${itemInfo.name}` : (mode === 'create' ? 'Inventarartikel erstellen' : 'Inventarartikel bearbeiten')}}</h1>
    </template>
    <template #right>
      <ButtonWithConfirm
          color="rose"
          variant="outline"
          @confirmed="dataStore.updateItem('inventoryitems',{...itemInfo, archived: true})"
          v-if="mode === 'edit'"
      >
        <template #button>
          Archivieren
        </template>
        <template #header>
          <span class="text-md text-black font-bold">Archivieren bestätigen</span>
        </template>
        Möchten Sie den Inventarartikel {{itemInfo.name}} wirklich archivieren?
      </ButtonWithConfirm>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('inventoryitems',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-if="mode === 'create'"
          @click="dataStore.createNewItem('inventoryitems',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          v-if="mode === 'create'"
          class="ml-2"
          @click="dataStore.createNewItem('inventoryitems',itemInfo);
          itemInfo = {
    name: null,
    description: null,
  quantity: 0
}"
      >
        Erstellen + Neu
      </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/${itemInfo.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UTabs
    :items="[{label: 'Informationen'}]"
    v-if="itemInfo && mode == 'show'"
    class="p-5"
  >
    <template #item="{item}">
      <div v-if="item.label === 'Informationen'" class="flex-row flex mt-5">
        <div class="w-1/2 mr-5">
          <UCard>
            <UAlert
                v-if="itemInfo.archived"
                color="rose"
                variant="outline"
                title="Objekt archiviert"
                icon="i-heroicons-light-bulb"
                class="mb-5"
            />
            <table class="w-full">
              <tr>
                <td>Name: </td>
                <td>{{itemInfo.name}}</td>
              </tr>
              <tr v-if="itemInfo.currentSpace">
                <td>Lagerplatz: </td>
                <td>{{dataStore.getSpaceById(itemInfo.currentSpace).spaceNumber}} - {{dataStore.getSpaceById(itemInfo.currentSpace).description}}</td>
              </tr>
              <tr>
                <td>Seriennummer:</td>
                <td>{{itemInfo.serialNumber}}</td>
              </tr>
              <tr>
                <td>Menge:</td>
                <td>{{itemInfo.quantity > 0 ? itemInfo.quantity : 'Einzelarktikel'}}</td>
              </tr>
              <tr>
                <td>Artikelnummer:</td>
                <td>{{itemInfo.articleNumber}}</td>
              </tr>
              <tr>
                <td>Hersteller:</td>
                <td>{{itemInfo.manufacturer}}</td>
              </tr>
              <tr>
                <td>Herstellernummer:</td>
                <td>{{itemInfo.manufacturerNumber}}</td>
              </tr>
              <tr>
                <td>Lieferant:</td>
                <td>{{itemInfo.vendor ? itemInfo.vendor.name : ''}}</td>
              </tr>
              <tr>
                <td>Kaufdatum:</td>
                <td>{{itemInfo.purchaseDate ? dayjs(itemInfo.purchaseDate).format("DD.MM.YYYY") : ''}}</td>
              </tr>
              <tr>
                <td>Wert bei Kauf:</td>
                <td>{{itemInfo.purchasePrice ? itemInfo.purchasePrice.toFixed(2).replace(".",",") + " €" : ''}}</td>
              </tr>
              <tr>
                <td>Aktueller Wert:</td>
                <td>{{itemInfo.currentValue ? itemInfo.currentValue.toFixed(2).replace(".",",") + " €" : ''}}</td>
              </tr>
              <tr>
                <td>Beschreibung:</td>
                <td>{{itemInfo.description}}</td>
              </tr>
            </table>
          </UCard>

        </div>
        <div class="w-1/2">
          <UCard>
            <HistoryDisplay
                type="inventoryitem"
                v-if="itemInfo"
                render-headline
                :element-id="itemInfo.id"
            />
          </UCard>

        </div>
      </div>
    </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="itemInfo.serialNumber ? 'Menge deaktiviert durch Eingabe der Seriennummer' : 'Für Einzelartikel Menge gleich 0'"
        >
          <UInput
              type="number"
              v-model="itemInfo.quantity"
              :disabled="itemInfo.serialNumber"
          />
        </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="Wert bei Kauf:"
        >
          <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>
        <UFormGroup
            label="Aktueller Wert:"
        >
          <UInput
              v-model="itemInfo.currentValue"
              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>
td {
  border-bottom: 1px solid lightgrey;
  vertical-align: top;
  padding-bottom: 0.15em;
  padding-top: 0.15em;
}
</style>