<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 folders = ref([])
const setup = async () => {
  const {data} = await supabase.from("folders").select().eq("tenant",useProfileStore().currentTenant)

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

    console.log(folder)

    const addParent = (folder) => {
      console.log(folder)
      name = `${folder.name} > ${name}`

      if(folder.parent){
        addParent(folder)
      } 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,
      })
    }
  })
}

setup()


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

const updateDocument = async () => {
  console.log("Update")

  const {url, ...objData} = props.documentData
  delete objData.url
  delete objData.filetags

  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"})
    //openShowModal.value = false
  }
}

const archiveDocument = () => {
  //documentData.tags.push("Archiviert")
  //updateDocument()
}

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 = () => {
  if(resourceToAssign.value === "project") {
    itemOptions.value = dataStore.projects
  } else if(resourceToAssign.value === "customer") {
    itemOptions.value = dataStore.customers
  } else if(resourceToAssign.value === "vendor") {
    itemOptions.value = dataStore.vendors
  } else if(resourceToAssign.value === "vehicle") {
    itemOptions.value = dataStore.vehicles
  } else if(resourceToAssign.value === "product") {
    itemOptions.value = dataStore.products
  } else if(resourceToAssign.value === "plant") {
    itemOptions.value = dataStore.plants
  } else if(resourceToAssign.value === "contract") {
    itemOptions.value = dataStore.contracts
  } else {
    itemOptions.value =  []
  }
}
getItemsBySelectedResource()

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

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

  if(error) {
    console.log(error)
    toast.add({title: "Fehler beim verschieben", color:"rose"})
  } else {
    toast.add({title: "Datei verschoben"})
  }
  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.filetags.includes('Bild')"

          />
          <img
              class=" w-full"
              :src="props.documentData.url"
              alt=""
              v-else
          />
        </div>
        <div class="w-2/3 p-5">
          <UButtonGroup>
            <!--          <UButton
                        @click="archiveDocument"
                      >
                        Archivieren
                      </UButton>-->
            <UButton
                :to="props.documentData.url"
                variant="outline"
                icon="i-heroicons-arrow-top-right-on-square"
                target="_blank"
            >
              Öffnen
            </UButton>
          </UButtonGroup>

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

          <USelectMenu
            v-model="folderToMoveTo"
            value-attribute="id"
            option-attribute="name"
            @change="moveFile"
            :options="folders"
          />
        </div>
      </div>
    </UCard>
  </UModal>
</template>

<style scoped>

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

</style>