<template>
  <div>
    <div class="controlHeader">
      <UButton @click="uploadModalOpen = true">Hochladen</UButton>
      <UModal
        v-model="uploadModalOpen"
      >
        <UCard class="p-4">

          <template #header>
            Datei hochladen
          </template>

          <UFormGroup
              label="Datei:"
          >
            <UInput
                type="file"
                id="fileUploadInput"
            />
          </UFormGroup>
          <UFormGroup
            label="Name:"
            class="mt-3"
          >
            <UInput
                v-model="fileUploadFormData.name"
            />
          </UFormGroup>
          <UFormGroup
            label="Tags:"
            class="mt-3"
          >
            <USelectMenu
                multiple
                searchable
                searchable-placeholder="Suchen..."
                :options="tags"
                v-model="fileUploadFormData.tags"
            />
          </UFormGroup>

          <template #footer>
            <UButton
                class="mt-3"
                @click="uploadFile"
            >Hochladen</UButton>
          </template>


        </UCard>

      </UModal>
<!--      <USelectMenu :options="sortOptions"/>-->
    </div>
    <div class="documentList">
      <USlideover
        v-model="showDocumentModal"
        fullscreen
      >
        <UCard>
          <template #header>
            {{selectedDocument.attributes.name}}
          </template>
<!--          <a
              v-if="selectedDocument.attributes"
              target="_blank"
              :href="`http://localhost:1337${selectedDocument.attributes.file.data.attributes.url}`"
              class="p-2"
          >
            Anzeigen


          </a>-->

          <UFormGroup
              label="Tags:"
          >
            <USelectMenu
                v-if="selectedDocument.attributes"
                multiple
                searchable
                searchable-placeholder="Suchen..."
                :options="tags"
                v-on:change="update('documents',selectedDocument.id, {tags: selectedDocument.attributes.tags})"
                v-model="selectedDocument.attributes.tags"
            />
          </UFormGroup>

          <UFormGroup
              label="Status:"
              class="mb-3"
          >
            <USelectMenu
                :options="states"
                v-model="selectedDocument.attributes.state"
                v-on:change="update('documents',selectedDocument.id,{state: selectedDocument.attributes.state})"
            />
          </UFormGroup>

          <div>
            <VuePDF
                ref="vuePDFRef"
                :pdf="pdf"
                fit-parent
                :page="page"
            />
          </div>
          <div class="mt-3">
            <UButton @click="page = page > 1 ? page - 1 : page">
              Prev
            </UButton>
            <span class="mx-3">{{ page }} / {{ pages }}</span>
            <UButton @click="page = page < pages ? page + 1 : page">
              Next
            </UButton>
          </div>

        </UCard>
      </USlideover>
      <a
          v-for="document in documents.filter(doc => doc.attributes.state != 'Archiviert')" class="documentListItem"
          @click="openDocument(document)"
      >
        <div>
          {{document.attributes.name}}<br>
          <UBadge
              v-for="tag in document.attributes.tags"
              variant="outline"
              color="primary"
          >{{tag}}</UBadge>
          <UBadge
            color="rose"
            variant="outline"
          >{{document.attributes.state}}</UBadge>

        </div>
      </a>
    </div>

<!--    <div class="documentPreview" v-if="selectedDocument.attributes">
      <UFormGroup
        label="Tags:"
      >
        <USelectMenu
            v-if="selectedDocument.attributes"
            multiple
            searchable
            searchable-placeholder="Suchen..."
            :options="tags"
            v-on:change="update('documents',selectedDocument.id, {tags: selectedDocument.attributes.tags})"
            v-model="selectedDocument.attributes.tags"
        />
      </UFormGroup>

      <UFormGroup
        label="Status:"
      >
        <USelectMenu
            :options="states"
            v-model="selectedDocument.attributes.state"
            v-on:change="update('documents',selectedDocument.id,{state: selectedDocument.attributes.state})"
        />
      </UFormGroup>
      <h4 v-if="selectedDocument.attributes">{{selectedDocument.attributes.name}}</h4>
&lt;!&ndash;      <embed src="http://localhost:1337/uploads/RE_1748755_cb0b16cd30.pdf">&ndash;&gt;
      {{selectedDocument}}

    </div>-->
  </div>

</template>

<script setup>
definePageMeta({
  middleware: "auth"
})

const sortOptions = ['Hinzugefügt',"Bearbeitet","Name"]

const {find,create, update} = useStrapi4()
const client = useStrapiClient()
const strapiMediaUrl = useStrapiMedia()
const documents = (await find('documents',{populate: "*"})).data

import { VuePDF, usePDF } from '@tato30/vue-pdf'

const page = ref(1)
const vuePDFRef = ref(null)
const pdfSource = ref("https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf")
const { pdf, pages } = usePDF(pdfSource)

const uploadModalOpen = ref(false)
let fileUploadData = null
const fileUploadFormData = ref({
  name: "",
  tags: ["Dokument"]
})

let tags = ["Eingangsrechnung","Ausgangrechnung","Mahnung", "Dokument"]
let states = ["Eingang", "Zugeordnet", "Archiviert"]

const uploadFile = async () => {
  try {

    fileUploadData = document.getElementById("fileUploadInput").files[0]

    let formData = new FormData()
    formData.append('files.file', fileUploadData)

    formData.append('data', JSON.stringify(fileUploadFormData.value))

    const {data} = await client("/documents", {
      method: "POST",
      body: formData
    })
  }
  catch (error) { alert(error)}


  uploadModalOpen.value = false;
  console.log("test")
}

const updateDocument = async () => {
  await update('documents', selectedDocument.id, {tags: selectedDocument.attributes.tags, state: selectedDocument.attributes.state})
}



const selectedDocument = ref({})
const showDocumentModal = ref(false)
const openDocument = (document) => {
  selectedDocument.value = document
  pdfSource.value = `${strapiMediaUrl}${document.attributes.file.data.attributes.url}`
  showDocumentModal.value = true

}

</script>

<style scoped>
#main {

  padding:10px;
}

.controlHeader {
  grid-area: headerleft;
}

.documentList {
  grid-area: main;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  max-width: 80vw;
  min-height: 75vh;
  margin-right: 5vw;
  margin-top: 1em;
}

.documentListItem {
  width: 15vw;
  height: 15vh;
  margin-right: 1em;
  padding:1em;
  border: 1px solid lightgrey;
  border-radius: 15px;
}

.documentListItem:hover {
  border: 1px solid #69c350;
  cursor: pointer;
}

.documentPreview {
  grid-area: right;
  width: 30vw;
}
</style>