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

definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const supabase = useSupabaseClient()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const id = ref(route.params.id ? route.params.id : null )
const numberRange  = useNumberRange("vendors")

let currentItem = ref(null)



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

//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
}

const editItem = async () => {
  router.push(`/vendors/edit/${currentItem.value.id}`)
  setupPage()
}

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

}

setupPage()
</script>

<template>
  <h1
      class=" mb-3 font-bold text-2xl truncate"
      v-if="currentItem "
  >Lieferant: {{currentItem.name}}</h1>
  <UTabs
    :items="[{label: 'Informationen'},{label: 'Logbuch'},{label: 'Ansprechpartner'},{label: 'Dokumente'}]"
    v-if="currentItem && mode == 'show'"
  >
    <template #item="{item}">
      <UCard class="mt-5">
        <div v-if="item.label === 'Informationen'">
          <Toolbar>
            <UButton
                v-if="mode == 'show' && currentItem.id"
                @click="editItem"
            >
              Bearbeiten
            </UButton>
          </Toolbar>

          <div v-if="currentItem.infoData" class="text-wrap">
            <p v-if="currentItem.infoData.street">Straße + Hausnummer: {{currentItem.infoData.street}}</p>
            <p v-if="currentItem.infoData.zip && currentItem.infoData.city">PLZ + Ort: {{currentItem.infoData.zip}} {{currentItem.infoData.city}}</p>
            <p v-if="currentItem.infoData.tel">Telefon: {{currentItem.infoData.tel}}</p>
            <p v-if="currentItem.infoData.email">E-Mail: {{currentItem.infoData.email}}</p>
            <p v-if="currentItem.infoData.web">Web: {{currentItem.infoData.web}}</p>
            <p v-if="currentItem.infoData.ustid">USt-Id: {{currentItem.infoData.ustid}}</p>
          </div>
        </div>
        <div v-else-if="item.label === 'Logbuch'">
          <HistoryDisplay
              type="vendor"
              v-if="currentItem"
              :element-id="currentItem.id"
          />
        </div>
        <div v-else-if="item.label === 'Ansprechpartner'">
          <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>

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

          <DocumentList
              :documents="dataStore.getDocumentsByVendorId(currentItem.id)"
          />
        </div>
      </UCard>
    </template>
  </UTabs>
  <UCard v-else-if="mode === 'edit' || mode === 'create'" >
    <template #header v-if="mode === 'edit'">
      {{itemInfo.name}}
    </template>

    <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"
      />
    </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="E-Mail:"
    >
      <UInput
          v-model="itemInfo.infoData.email"
      />
    </UFormGroup>
    <UFormGroup
        label="Webseite:"
    >
      <UInput
          v-model="itemInfo.infoData.web"
      />
    </UFormGroup>
    <UFormGroup
        label="USt-Id:"
    >
      <UInput
          v-model="itemInfo.infoData.ustid"
      />
    </UFormGroup>


    <template #footer>
      <UButton
          v-if="mode == 'edit'"
          @click="dataStore.updateItem('vendors',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode == 'create'"
          @click="dataStore.createNewItem('vendors',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="cancelEditorCreate"
          color="red"
          class="ml-2"
      >
        Abbrechen
      </UButton>
    </template>

  </UCard>


</template>

<style scoped>

</style>