<script setup>

const toast = useToast()
const supabase = useSupabaseClient()
const dataStore = useDataStore()
const modal = useModal()
const props = defineProps({
  documentData: {
    type: Object,
    required: true
  },
  openShowModal: {
    type: Boolean,
    required: false,
  },
  returnEmit: {
    type: Boolean
  },

})

const emit = defineEmits(["updateNeeded"])

const folders = ref([])

const filetypes = ref([])

const setup = async () => {
  const {data} = await supabase.from("folders").select().eq("tenant",useProfileStore().currentTenant)

  data.forEach(folder => {
    let name = folder.name

    const addParent = (item) => {
      name = `${item.name} > ${name}`

      if(item.parent){
        addParent(data.find(i => i.id === item.parent))
      } else {
        folders.value.push({
          id: folder.id,
          name: name,
        })
      }
    }

    if(folder.parent) {
      addParent(data.find(i => i.id === folder.parent))
    } else {
      folders.value.push({
        id: folder.id,
        name: folder.name,
      })
    }
  })

  filetypes.value = await useSupabaseSelect("filetags")
}

setup()


//Functions
const openDocument = async () => {
  //selectedDocument.value = doc
  openShowModal.value = true
  console.log("open")
}

const updateDocument = async () => {
  const {url, ...objData} = props.documentData
  delete objData.url
  delete objData.filetags

  if(objData.project) objData.project = objData.project.id
  if(objData.customer) objData.customer = objData.customer.id
  if(objData.contract) objData.contract = objData.contract.id
  if(objData.vendor) objData.vendor = objData.vendor.id
  if(objData.plant) objData.plant = objData.plant.id
  if(objData.createddocument) objData.createddocument = objData.createddocument.id
  if(objData.vehicle) objData.vehicle = objData.vehicle.id
  if(objData.product) objData.product = objData.product.id
  if(objData.profile) objData.profile = objData.profile.id
  if(objData.check) objData.check = objData.check.id
  if(objData.inventoryitem) objData.inventoryitem = objData.inventoryitem.id
  if(objData.incominginvoice) objData.incominginvoice = objData.incominginvoice.id


  const {data,error} = await supabase
      .from("files")
      .update(objData)
      .eq('id',objData.id)
      .select()

  if(error) {
    console.log(error)
  } else {
    toast.add({title: "Datei aktualisiert"})
    modal.close()
    emit("updateNeeded")
    //openShowModal.value = false
  }
}

const archiveDocument = async () => {
  props.documentData.archived = true
  await updateDocument()

  const {data,error} = await supabase.from("historyitems").insert({
    createdBy: useProfileStore().activeProfile.id,
    tenant: useProfileStore().currentTenant,
    text: "Datei archiviert",
    file: props.documentData.id
  })

  modal.close()
  emit("update")
}

const resourceOptions = ref([
    {label: 'Projekt', value: 'project', optionAttr: "name"},
  {label: 'Kunde', value: 'customer', optionAttr: "name"},
  {label: 'Lieferant', value: 'vendor', optionAttr: "name"},
  {label: 'Fahrzeug', value: 'vehicle', optionAttr: "licensePlate"},
  {label: 'Objekt', value: 'plant', optionAttr: "name"},
  {label: 'Vertrag', value: 'contract', optionAttr: "name"},
  {label: 'Produkt', value: 'product', optionAttr: "name"}
])
const resourceToAssign = ref("project")
const itemOptions = ref([])
const idToAssign = ref(null)
const getItemsBySelectedResource = async () => {
  if(resourceToAssign.value === "project") {
    itemOptions.value = await useSupabaseSelect("projects")
  } else if(resourceToAssign.value === "customer") {
    itemOptions.value = await useSupabaseSelect("customers")
  } else if(resourceToAssign.value === "vendor") {
    itemOptions.value = await useSupabaseSelect("vendors")
  } else if(resourceToAssign.value === "vehicle") {
    itemOptions.value = await useSupabaseSelect("vehicles")
  } else if(resourceToAssign.value === "product") {
    itemOptions.value = await useSupabaseSelect("products")
  } else if(resourceToAssign.value === "plant") {
    itemOptions.value = await useSupabaseSelect("plants")
  } else if(resourceToAssign.value === "contract") {
    itemOptions.value = await useSupabaseSelect("contracts")
  } else {
    itemOptions.value =  []
  }
}
getItemsBySelectedResource()

const updateDocumentAssignment = async () => {
  props.documentData[resourceToAssign.value] = idToAssign.value
  await updateDocument()
}

const folderToMoveTo = ref(null)
const moveFile = async () => {
  console.log(folderToMoveTo.value)
  const {data,error} = await supabase
    .from("files")
    .update({folder: folderToMoveTo.value})
    .eq("id",props.documentData.id)
    .select()

  if(error) {
    console.log(error)
    toast.add({title: "Fehler beim verschieben", color:"rose"})
  } else {
    toast.add({title: "Datei verschoben"})
    console.log(data)
  }
  modal.close()
}



</script>

<template>
  <UModal fullscreen >
    <UCard :ui="{ body: { base: 'flex-1' }, ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
      <template #header>
        <div class="flex flex-row justify-between">
          <div class="flex items-center gap-2">
            <UBadge
                v-for="tag in props.documentData.filetags"
            >
              {{tag.name}}
            </UBadge>
          </div>
          <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1" @click="modal.close()" />
        </div>

      </template>
      <div class="flex flex-row">
        <div class="w-1/3">
          <object
              class="bigPreview"
              :data="`${props.documentData.url}#toolbar=0&navpanes=0&scrollbar=0`"
              type="application/pdf"
              v-if="props.documentData.path.includes('pdf')"

          />
          <img
              class=" w-full"
              :src="props.documentData.url"
              alt=""
              v-else
          />
        </div>
        <div class="w-2/3 p-5">
          <UButtonGroup>
            <ButtonWithConfirm
                color="rose"
                variant="outline"
                @confirmed="archiveDocument"
            >
              <template #button>
                Archivieren
              </template>
              <template #header>
                <span class="text-md text-black font-bold">Archivieren bestätigen</span>
              </template>
              Möchten Sie die Datei wirklich archivieren?
            </ButtonWithConfirm>

            <UButton
                :to="props.documentData.url"
                variant="outline"
                icon="i-heroicons-arrow-top-right-on-square"
                target="_blank"
            >
              Öffnen
            </UButton>
          </UButtonGroup>

          <UDivider>Zuweisungen</UDivider>

          <table class="w-full">
            <tr v-if="props.documentData.project">
              <td>Projekt</td>
              <td>
                <nuxt-link :to="`/standardEntity/projects/show/${props.documentData.project.id}`">{{props.documentData.project.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.customer">
              <td>Kunde</td>
              <td>
                <nuxt-link :to="`/standardEntity/customers/show/${props.documentData.customer.id}`">{{props.documentData.customer.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.vendor">
              <td>Lieferant</td>
              <td>
                <nuxt-link :to="`/standardEntity/vendors/show/${props.documentData.vendor.id}`">{{props.documentData.vendor.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.createddocument">
              <td>Ausgangsbeleg</td>
              <td>
                <nuxt-link :to="`/createDocument/show/${props.documentData.createddocument.id}`">{{props.documentData.createddocument.documentNumber}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.plant">
              <td>Objekt</td>
              <td>
                <nuxt-link :to="`/standardEntity/plants/show/${props.documentData.plant.id}`">{{props.documentData.plant.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.contract">
              <td>Vertrag</td>
              <td>
                <nuxt-link :to="`/standardEntity/contracts/show/${props.documentData.contract.id}`">{{props.documentData.contract.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.vehicle">
              <td>Fahrzeug</td>
              <td>
                <nuxt-link :to="`/standardEntity/vehicles/show/${props.documentData.vehicle.id}`">{{props.documentData.vehicle.licensePlate}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.product">
              <td>Artikel</td>
              <td>
                <nuxt-link :to="`/standardEntity/products/show/${props.documentData.product.id}`">{{props.documentData.product.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.inventoryitem">
              <td>Inventarartikel</td>
              <td>
                <nuxt-link :to="`/standardEntity/inventoryitem/show/${props.documentData.inventoryitem.id}`">{{props.documentData.inventoryitem.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.check">
              <td>Überprüfung</td>
              <td>
                <nuxt-link :to="`/standardEntity/checks/show/${props.documentData.check.id}`">{{props.documentData.check.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.profile">
              <td>Mitarbeiter</td>
              <td>
                <nuxt-link :to="`/profiles/show/${props.documentData.profile.id}`">{{props.documentData.profile.fullName}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.incominginvoice">
              <td>Eingangsrechnung</td>
              <td>
                <nuxt-link :to="`/incomingInvoices/show/${props.documentData.incominginvoice.id}`">{{props.documentData.incominginvoice.reference}}</nuxt-link>
              </td>
            </tr>
          </table>

          <UDivider class="my-3">Datei zuweisen</UDivider>

          <UFormGroup
              label="Resource auswählen"
          >
            <USelectMenu
                :options="resourceOptions"
                v-model="resourceToAssign"
                value-attribute="value"
                option-attribute="label"
                @change="getItemsBySelectedResource"
            >

            </USelectMenu>
          </UFormGroup>
          <UFormGroup
              label="Eintrag auswählen:"
          >

          </UFormGroup>

          <USelectMenu
              :options="itemOptions"
              v-model="idToAssign"
              :option-attribute="resourceOptions.find(i => i.value === resourceToAssign)? resourceOptions.find(i => i.value === resourceToAssign).optionAttr : 'name'"
              value-attribute="id"
              @change="updateDocumentAssignment"
          ></USelectMenu>

          <UDivider class="my-5">Datei verschieben</UDivider>

          <InputGroup class="w-full">
            <USelectMenu
                class="flex-auto"
                v-model="folderToMoveTo"
                value-attribute="id"
                option-attribute="name"
                :options="folders"
            />
            <UButton
              @click="moveFile"
              variant="outline"
            >Verschieben</UButton>
          </InputGroup>

          <UDivider class="my-5">Dateityp</UDivider>

          <InputGroup class="w-full">
            <USelectMenu
                class="flex-auto"
                v-model="props.documentData.type"
                value-attribute="id"
                option-attribute="name"
                :options="filetypes"
                @change="updateDocument"
            />
          </InputGroup>

        </div>
      </div>
    </UCard>
  </UModal>
</template>

<style scoped>

.bigPreview {
  width: 100%;
  aspect-ratio: 1/ 1.414;
}

</style>