<template>
  <div id="main">






    <div
      class="previewDoc"
    >
      <embed
          v-if="currentDocument"
          :src="currentDocument.url + '#toolbar=0&navpanes=0&scrollbar=0&statusbar=0&messages=0&scrollbar=0'"

      >

    </div>
    <div
      class="inputData"
    >
      <UFormGroup label="Lieferant:" required>
        <USelectMenu
          v-model="itemInfo.vendor"
          :options="vendors"
          option-attribute="name"
          value-attribute="id"
          searchable
          :search-attributes="['name','vendorNumber']"
        >
          <template #label>
            {{vendors.find(vendor => vendor.id === itemInfo.vendor) ? vendors.find(vendor => vendor.id === itemInfo.vendor).name : 'Lieferant auswählen'}}
          </template>
        </USelectMenu>
      </UFormGroup>

      <UFormGroup
          class="mt-3"
          label="Rechnungsreferenz:"
          required
      >
        <UInput
          v-model="itemInfo.reference"
        />
      </UFormGroup>

      <InputGroup class="mt-3" gap="2">
        <UFormGroup label="Rechnungsdatum:" required>
          <UPopover :popper="{ placement: 'bottom-start' }">
            <UButton icon="i-heroicons-calendar-days-20-solid" :label="itemInfo.date ? dayjs(itemInfo.date).format('DD.MM.YYYY') : 'Datum auswählen'" />

            <template #panel="{ close }">
              <LazyDatePicker v-model="itemInfo.date" @close="close" />
            </template>
          </UPopover>
        </UFormGroup>

        <UFormGroup label="Fälligkeitsdatum:" required>
          <UPopover :popper="{ placement: 'bottom-start' }">
            <UButton icon="i-heroicons-calendar-days-20-solid" :label="itemInfo.dueDate ? dayjs(itemInfo.dueDate).format('DD.MM.YYYY') : 'Datum auswählen'" />

            <template #panel="{ close }">
              <LazyDatePicker v-model="itemInfo.dueDate" @close="close" />
            </template>
          </UPopover>
        </UFormGroup>
      </InputGroup>



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

      <UFormGroup label="Betrag:" required>
        <UInput
          type="number"
          step="0.01"
          v-model="itemInfo.amount"
        >
          <template #trailing>
            <span class="text-gray-500 dark:text-gray-400 text-xs">EUR</span>
          </template>
        </UInput>
      </UFormGroup>

      <InputGroup class="mt-3">
        <UButton
            @click="updateItem"
        >
          Speichern
        </UButton>
      </InputGroup>

      <DevOnly>
        {{itemInfo}}<br>
        {{currentVendorInvoice}}<br>
        {{currentDocument}}
      </DevOnly>


    </div>
  </div>
</template>

<script setup>
import InputGroup from "~/components/InputGroup.vue";
import * as dayjs from "dayjs";

const supabase = useSupabaseClient()
const route = useRoute()
const toast = useToast()

const {vendors} = storeToRefs(useDataStore())
const {getVendorInvoiceById, getDocumentById, fetchVendorInvoices} = useDataStore()

let currentVendorInvoice = null
let currentDocument  = ref(null)
//Working
const mode = ref(route.params.mode || "show")


//Functions
const setupPage = async () => {
  if(mode.value === "show" || mode.value === "edit"){
    currentVendorInvoice = await getVendorInvoiceById(Number(useRoute().params.id))
    currentDocument.value = await getDocumentById(currentVendorInvoice.document)
  }

  if(mode.value === "edit") itemInfo.value = currentVendorInvoice



}





const itemInfo = ref({
  vendor: 0,
  reference: "",
  date:  null,
  dueDate: null,
  paymentType: "",
  description: "",
  state: "Entwurf"
})

const updateItem = async () => {
  const {error} = await supabase
      .from("vendorInvoices")
      .update(itemInfo.value)
      .eq('id',itemInfo.value.id)
  if(error) {
    console.log(error)
  } else {
    mode.value = "show"
    /*itemInfo.value = {
      id: 0,
    }*/
    toast.add({title: "Eingangsrechnung erfolgreich gespeichert"})
    fetchVendorInvoices()
  }
}



setupPage()
</script>

<style scoped>
#main {
  display: flex;
  flex-direction: row;
}

.previewDoc {
  min-width: 50vw;
  min-height: 80vh;
}

.previewDoc embed {
  width: 90%;
  height: 100%;
}

.inputData {
  max-width: 40vw;
}




.lineItemRow {
  display: flex;
  flex-direction: row;
}
</style>