<script setup>
import axios from "axios";
import ZebraBrowserPrintWrapper from "zebra-browser-print-wrapper"
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://${dataStore.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 #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: 'Logbuch'},{label: 'Bestand'},{label: 'Inventarartikel'}]"
        v-if="itemInfo && mode == 'show'"
        class="p-5"
    >
      <template #item="{item}">
        <UCard class="mt-5">
          <div v-if="item.label === 'Informationen'">
            <div class="truncate">
              <p>Übergeordneter Lagerplatz: <router-link v-if="itemInfo.parentSpace" :to="`/spaces/show/${itemInfo.parentSpace.id}`">{{itemInfo.parentSpace.spaceNumber}} - {{itemInfo.parentSpace.description}}</router-link></p>
              <p>Beschreibung: <br>{{itemInfo.description}}</p>
            </div>


          </div>
          <div v-else-if="item.label === 'Logbuch'">

          </div>
          <div v-else-if="item.label === 'Bestand'">
            <div v-if="spaceProducts.length > 0">
              <p class="mt-5">Artikel in diesem Lagerplatz</p>

              <table>
                <tr>
                  <th class="text-left">Artikel</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>
          </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>
        </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="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>

</style>