<script setup>

definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  'backspace': () => {
    router.push("/vendors")
  },
  'arrowleft': () => {
    if(openTab.value > 0){
      openTab.value -= 1
    }
  },
  'arrowright': () => {
    if(openTab.value < 1) {
      openTab.value += 1
    }
  },
})

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



//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
  infoData: {}
})
const oldItemInfo = ref({})

//Functions
const setupPage = () => {
  if (mode.value === "show" || mode.value === "edit") {
    currentItem.value = dataStore.getVendorById(Number(useRoute().params.id))
  }

  if (mode.value === "edit") itemInfo.value = currentItem.value
  if(currentItem.value) oldItemInfo.value = JSON.parse(JSON.stringify(currentItem.value))

}

const setCityByZip = async () => {
  itemInfo.value.infoData.city = await useZipCheck(itemInfo.value.infoData.zip)
}

setupPage()
</script>

<template>
  <UDashboardNavbar
      :title="currentItem ? `Lieferant: ${currentItem.name}` : (mode === 'create' ? 'Lieferant erstellen' : 'Lieferant bearbeiten')"
      :ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
  >
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/vendors`)"
      >
        Lieferanten
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="currentItem"
          :class="['text-xl','font-medium']"
      >{{currentItem ? `Lieferant: ${currentItem.name}` : (mode === 'create' ? 'Lieferant erstellen' : 'Lieferant bearbeiten')}}</h1>
    </template>
    <template #right>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('vendors',itemInfo,oldItemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('vendors',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="router.push(currentItem.id ? `/vendors/show/${currentItem.id}` : '/vendors/show')"
          color="red"
          class="ml-2"
          v-if="mode === 'edit' || mode === 'create'"
      >
        Abbrechen
      </UButton>
      <UButton
          v-if="mode === 'show'"
          @click="router.push(`/vendors/edit/${currentItem.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UTabs
    :items="[{label: 'Informationen'},{label: 'Dokumente'}]"
    v-if="currentItem && mode == 'show'"
    class="p-5"
    v-model="openTab"
  >
    <template #item="{item}">
      <div v-if="item.label === 'Informationen'" class="mt-5 flex">
        <div class="w-1/2 mr-5">
          <UCard>
            <div v-if="currentItem.infoData" class="text-wrap">
              <p>Straße + Hausnummer: {{currentItem.infoData.street ? currentItem.infoData.street : ""}}</p>
              <p>PLZ + Ort: {{currentItem.infoData.zip}} {{currentItem.infoData.city}}</p>
              <p>Telefon: {{currentItem.infoData.tel}}</p>
              <p>E-Mail: {{currentItem.infoData.email}}</p>
              <p>Web: {{currentItem.infoData.web}}</p>
              <p>USt-Id: {{currentItem.infoData.ustid}}</p>
              <p>SEPA Mandat: {{currentItem.hasSEPA ? "Ja" : "Nein"}}</p>
              <p>Notizen:<br> {{currentItem.notes}}</p>
            </div>
          </UCard>
          <UCard class="mt-5">
            <Toolbar>
              <UButton
                  @click="router.push(`/contacts/create?vendor=${currentItem.id}`)"
              >
                + Ansprechpartner
              </UButton>
            </Toolbar>
            <UTable
                :rows="dataStore.getContactsByVendorId(currentItem.id)"
                @select="(row) => router.push(`/contacts/show/${row.id}`)"
                :columns="[{label: 'Anrede', key: 'salutation'},{label: 'Name', key: 'fullName'},{label: 'Rolle', key: 'role'}]"
                :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine zugehörigen Ansprechpartner' }"

            >

            </UTable>
          </UCard>
        </div>
        <div class="w-1/2">
          <UCard class="h-full">
            <HistoryDisplay
                type="vendor"
                v-if="currentItem"
                :element-id="currentItem.id"
                :render-headline="true"
            />
          </UCard>
        </div>
      </div>


      <UCard class="mt-5" v-else>
        <div v-if="item.label === 'Dokumente'">
          <InputGroup>
            <DocumentUpload
                type="vendor"
                :element-id="currentItem.id"
            />
          </InputGroup>

          <DocumentList
              :documents="dataStore.getDocumentsByVendorId(currentItem.id)"
          />
        </div>
      </UCard>
    </template>
  </UTabs>
  <UForm
      v-else-if="mode === 'edit' || mode === 'create'"
      class="p-5"
  >
    <UFormGroup
        label="Name:"
    >
      <UInput
          v-model="itemInfo.name"
      />
    </UFormGroup>
    <UFormGroup
        label="Lieferantennr.:"
    >
      <UInput
          v-model="itemInfo.vendorNumber"
          placeholder="Leer lassen für automatisch generierte Nummer"
      />
    </UFormGroup>
    <UFormGroup
        label="Straße + Hausnummer"
    >
      <UInput
          v-model="itemInfo.infoData.street"
      />
    </UFormGroup>
    <UFormGroup
        label="Postleitzahl"
    >
      <UInput
          v-model="itemInfo.infoData.zip"
          @focusout="setCityByZip"
      />
    </UFormGroup>
    <UFormGroup
        label="Ort"
    >
      <UInput
          v-model="itemInfo.infoData.city"
      />
    </UFormGroup>
    <UFormGroup
        label="Land"
    >
      <USelectMenu
          :options="['Deutschland','Niederlande','Belgien','Italien', 'Frankreich','Irland','USA','Spanien', 'Schweden']"
          v-model="itemInfo.infoData.country"
      />
    </UFormGroup>

    <UFormGroup
        label="Telefon:"
    >
      <UInput
          v-model="itemInfo.infoData.tel"
      />
    </UFormGroup>

    <UFormGroup
        label="Notizen:"
    >
      <UTextarea
          v-model="itemInfo.notes"
      />
    </UFormGroup>
    <UFormGroup
        label="E-Mail:"
    >
      <UInput
          v-model="itemInfo.infoData.email"
      />
    </UFormGroup>
    <UFormGroup
        label="Webseite:"
    >
      <UInput
          v-model="itemInfo.infoData.web"
      />
    </UFormGroup>
    <UFormGroup
        label="SEPA Mandat abgeschlossen:"
    >
      <UCheckbox
          v-model="itemInfo.hasSEPA"
      />
    </UFormGroup>
    <UFormGroup
        label="USt-Id:"
    >
      <UInput
          v-model="itemInfo.infoData.ustid"
      />
    </UFormGroup>
  </UForm>
</template>

<style scoped>

</style>