<script setup>
import {useFunctions} from "~/composables/useFunctions.js";
import dayjs from "dayjs";

const profileStore = useProfileStore();

const preloadedContent = ref("")
const letterheads = ref([])
const itemInfo = ref({
  contentHTML: "",
  contentJSON: {},
  contentText: ""
})
const showDocument = ref(false)
const uri = ref("")
const openTab = ref("0")

const setupPage = async () => {
  letterheads.value = await useEntities("letterheads").select("*")

  preloadedContent.value = `<p></p><p></p><p></p>`
}

setupPage()

const onChangeTab = (index) => {
  openTab.value = String(index)

  if(String(index) === "1") {
    generateDocument()
  }
}

const getDocumentData = () => {
  /*const returnData = {
    adressLine: `${businessInfo.name}, ${businessInfo.street}, ${businessInfo.zip} ${businessInfo.city}`,
    recipient: [
      customerData.name,
      ... customerData.nameAddition ? [customerData.nameAddition] : [],
      ... contactData ? [`${contactData.firstName} ${contactData.lastName}`] : [],
      itemInfo.value.address.street,
      ... itemInfo.value.address.special ? [itemInfo.value.address.special] : [],
      `${itemInfo.value.address.zip} ${itemInfo.value.address.city}`,

    ],
  }*/

  const returnData = {
    adressLine: `Federspiel Technology UG, Am Schwarzen Brack 14, 26452 Sande`,
    recipient: [
      "Federspiel Technology",
      "UG haftungsbeschränkt",
      "Florian Federspiel",
      "Am Schwarzen Brack 14",
      "Zusatz",
      "26452 Sande",
    ],
    contentJSON: itemInfo.value.contentJSON,
  }

  return returnData
}

const generateDocument = async () => {
  const ownTenant = profileStore.ownTenant
  const path = letterheads.value[0].path

  uri.value = await useFunctions().useCreateLetterPDF(getDocumentData(), path)

  showDocument.value = true
}

const contentChanged = (content) => {
  itemInfo.value.contentHTML = content.html
  itemInfo.value.contentJSON = content.json
  itemInfo.value.contentText = content.text
}
</script>

<template>
  <UDashboardNavbar title="Anschreiben bearbeiten"/>
  {{itemInfo}}
  <UDashboardPanelContent>
    <UTabs v-model="openTab" @update:model-value="onChangeTab" :items="[{label: 'Editor'},{label: 'Vorschau'}]">
      <template #content="{item}">
        <div v-if="item.label === 'Editor'">
          <Tiptap
              class="mt-3"
              @updateContent="contentChanged"
              :preloadedContent="preloadedContent"
          />
        </div>
        <div v-else-if="item.label === 'Vorschau'">
          <object
              :data="uri"
              v-if="showDocument"
              type="application/pdf"
              class="w-full previewDocumentMobile"
          />
        </div>
      </template>
    </UTabs>
  </UDashboardPanelContent>

</template>

<style scoped>
.previewDocumentMobile {
  aspect-ratio: 1 / 1.414;
}
</style>
