<script setup>
import axios from "axios";
import ZebraBrowserPrintWrapper from "zebra-browser-print-wrapper"
import HistoryDisplay from "~/components/HistoryDisplay.vue";
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({
  spaceNumber: "",
  address: {
    streetNumber: "",
    city: "",
    zip:""
  }
})
const spaceTypes = ["Standort","Regalplatz", "Kiste", "Palettenplatz", "Sonstiges"]
const spaceProducts = ref([])
const spaceMovements = ref([])

const spaces = ref([])

//Functions
const setupPage = async () => {
  if(mode.value === "show"){
    itemInfo.value = await useSupabaseSelectSingle("spaces",route.params.id,"*, parentSpace(*), inventoryitems(*)")

    spaceMovements.value = await dataStore.getMovementsBySpace(itemInfo.value.id)
    spaceProducts.value = []
    spaceMovements.value.forEach(movement => {
      if(spaceProducts.value.filter(product => product.id === movement.productId).length === 0) spaceProducts.value.push(dataStore.getProductById(movement.productId))
    })


  } else if(mode.value === "edit") {
    itemInfo.value = await useSupabaseSelectSingle("spaces",route.params.id,"*")
  }

  if(mode.value === "edit" || mode.value === "create"){
    if(itemInfo.value){
      spaces.value = (await useSupabaseSelect("spaces",'*')).filter(i => i.id !== itemInfo.value.id)
    } else {
      spaces.value = (await useSupabaseSelect("spaces",'*'))
    }
  }







}

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

function getSpaceProductCount(productId) {
  let productMovements = spaceMovements.value.filter(movement => movement.productId === productId)
  let count = 0;
  productMovements.forEach(movement => count += movement.quantity)

  return count
}

/*
const printSpaceLabel = async () => {
  axios
      .post(`http://${profileStore.ownTenant.value.labelPrinterIp}/pstprnt`, `^XA^FO10,20^BCN,100^FD${itemInfo.value.spaceNumber}^XZ` )
      .then(console.log)
      .catch(console.log)
}
*/

const cityLoading = ref(false)
const setCityByZip = async () => {
  cityLoading.value = true
  itemInfo.value.address.city = await useZipCheck(itemInfo.value.address.zip)
  cityLoading.value = false
}


setupPage()
</script>

<template>
  <UDashboardNavbar :title="itemInfo ? itemInfo.name : (mode === 'create' ? 'Lagerplatz erstellen' : 'Lagerplatz bearbeiten')">
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/spaces`)"
      >
        Lagerplätze
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          :class="['text-xl','font-medium']"
      >{{itemInfo ? `Lagerplatz: ${itemInfo.spaceNumber} - ${itemInfo.description}` : (mode === 'create' ? 'Lagerplatz erstellen' : 'Lagerplatz bearbeiten')}}</h1>
    </template>
    <template #right>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('spaces',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('spaces',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(`/spaces/edit/${itemInfo.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardPanelContent>
    <UTabs
        :items="[{label: 'Informationen'},{label: 'Bestand'},{label: 'Inventarartikel'}]"
        v-if="itemInfo && mode === 'show'"
        class="p-5"
    >
      <template #item="{item}">
        <div v-if="item.label === 'Informationen'" class="flex mt-5">
          <div class="w-1/2 mr-5">
            <UCard>
              <div class="truncate">
                <table>
                  <tr>
                    <td>Typ:</td>
                    <td>{{itemInfo.type}}</td>
                  </tr>
                  <tr v-if="itemInfo.type !== 'Standort'">
                    <td>Übergeordneter Lagerplatz:</td>
                    <td><router-link v-if="itemInfo.parentSpace" :to="`/spaces/show/${itemInfo.parentSpace.id}`">{{itemInfo.parentSpace.spaceNumber}} - {{itemInfo.parentSpace.description}}</router-link></td>
                  </tr>
                  <tr v-if="itemInfo.type === 'Standort'">
                    <td>Adresse:</td>
                    <td>{{`${itemInfo.address.streetNumber}, ${itemInfo.address.zip} ${itemInfo.address.city}`}}</td>
                  </tr>
                  <tr>
                    <td>Beschreibung:</td>
                    <td>{{itemInfo.description}}</td>
                  </tr>
                </table>
              </div>
            </UCard>

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



        </div>
        <div v-else-if="item.label === 'Bestand'">
          <UCard>
            <div v-if="spaceProducts.length > 0">

              <table class="w-full">
                <tr>
                  <th class="text-left">Artikel in diesem Lagerplatz</th>
                  <th>Anzahl</th>
                  <th>Einheit</th>
                </tr>
                <tr v-for="product in spaceProducts">
                  <td>{{product.name}}</td>
                  <td>{{getSpaceProductCount(product.id)}}</td>
                  <td>{{dataStore.units.find(unit => unit.id === product.unit).name}}</td>
                </tr>

              </table>
            </div>
            <p v-else>Es befinden sich keine Artikel in diesem Lagerplatz</p>
          </UCard>

        </div>
        <div v-else-if="item.label === 'Inventarartikel'">
          <UAlert
              description="Hier werden alle Inventarartikel in diesem Lagerplatz aufgelistet"
              color="primary"
              variant="outline"
          />
          <UTable
              :rows="itemInfo.inventoryitems"
              :columns="[{label:'Name',key:'name'}]"
              @select="(row) => router.push(`/inventoryitems/show/${row.id}`)"
          >

          </UTable>
        </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="Typ:"
          >
            <USelectMenu
                :options="spaceTypes"
                v-model="itemInfo.type"
            >

            </USelectMenu>
          </UFormGroup>
          <UFormGroup
              label="Übergeordneter Lagerplatz:"
              v-if="itemInfo.type !== 'Standort'"
          >
            <USelectMenu
                :options="spaces"
                option-attribute="spaceNumber"
                value-attribute="id"
                v-model="itemInfo.parentSpace"
            >

            </USelectMenu>
          </UFormGroup>
        </div>
        <div class="w-1/2" v-if="itemInfo.type === 'Standort'">
          <UDivider>
            Ort
          </UDivider>
          <UFormGroup
              label="Straße + Hausnummer:"
          >
            <UInput
                v-model="itemInfo.address.streetNumber"
            />
          </UFormGroup>
          <UFormGroup
              label="PLZ + Ort:"
          >
            <InputGroup class="w-full">
              <UInput
                  v-model="itemInfo.address.zip"
                  placeholder="PLZ"
                  @focusout="setCityByZip"
              />
              <UInput
                  v-model="itemInfo.address.city"
                  placeholder="Ort"
                  class="flex-auto"
                  :disabled="cityLoading"

              />
            </InputGroup>

          </UFormGroup>
        </div>
      </div>


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

</template>

<style scoped>
td,th {
  padding-right: 2em;
  text-align: left;
}

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