<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>
          <UFormGroup
            label="Ordner:"
            class="mt-3"
          >
            <USelectMenu
                :options="folders"
                v-model="fileUploadFormData.folder"
                value-attribute="label"

            />
          </UFormGroup>

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


        </UCard>

      </UModal>
    </div>
    <div >
      <USlideover
        v-model="showDocumentModal"
        fullscreen
      >
        <UCard class="h-full">

          <embed
              class="bigPreview mb-3"
              :src="selectedDocument.url"
          />

          <UBadge
            v-for="tag in selectedDocument.tags"
          >
            {{tag}}
          </UBadge>


          <UFormGroup
            label="Ordner ändern:"
          >
            <USelectMenu
              :options="folders"
              v-on:change="changeFolder"
              v-model="newFolder"
              value-attribute="label"
            />
          </UFormGroup>




        </UCard>
      </USlideover>
<!-- TODO: Tab Height always Full      -->
      <UTabs
          :items="folders"
          orientation="vertical"
          v-model="tabOpen"
          :ui="{ wrapper: 'flex items-top gap-4', list: { width: 'w-72', padding: 'p-3' } }"
      >
        <template #item="{item}">
          <div class="documentList">
            <div
                v-if="documents.filter(doc => doc.folder === item.label).length > 0"
                v-for="document in documents.filter(doc => doc.folder === item.label)"
                class="documentListItem"
            >
              <embed
                  :src="document.url"
                  class="previewEmbed"
              />
              <UButton
                  @click="openDocument(document)"
                  class="mt-3"
              >
                <UIcon name="i-heroicons-eye-solid" />
              </UButton>

              <!--              {{document.name}}<br>-->
              <!--              <UBadge
                                v-for="tag in document.tags"
                                variant="outline"
                                color="primary"
                            >{{tag}}</UBadge>
                            <UBadge
                                color="rose"
                                variant="outline"
                            >{{document.state}}</UBadge>-->

            </div>
            <div v-else>
              <p>Keine Dokumente in diesem Ordner</p>
              <UButton
                  @click="uploadModalOpen = true"
              >
                Hochladen
              </UButton>
            </div>
          </div>
        </template>
      </UTabs>
    </div>
  </div>

</template>

<script setup>

definePageMeta({
  middleware: "auth"
})
const supabase = useSupabaseClient()
const user = useSupabaseUser()

const {documents} = storeToRefs(useDataStore())

const tabOpen = ref(0)
const uploadModalOpen = ref(false)
const fileUploadFormData = ref({
  tags: [],
  folder: "",
  object: "",
  path: ""
})

let tags = ["Eingangsrechnung","Ausgangrechnung","Mahnung", "Dokument"]
const folders = [
  {
    label: "Eingang",
  },
  {
    label: "Eingangsrechnungen"
  },
  {
    label: "Ausgangsrechnungen"
  },
  {
    label: "Fahrzeuge"
  },
  {
    label: "Dokumente"
  },
  {
    label: "Archiv"
  }
]
const uploadFile = async () => {
  const file = document.getElementById("fileUploadInput").files[0]

  const {data,error} = await supabase
      .storage
      .from("documents")
      .upload(`${user.value.app_metadata.tenant}/${fileUploadFormData.value.folder}/${file.name}`,file)

  const returnPath = data.path

  if(error) {

  } else {
    console.log(returnPath)
    const files = (await supabase.storage.from('documents').list(`${user.value.app_metadata.tenant}/${fileUploadFormData.value.folder}/`, {limit: 100, offset: 0, sortBy: { column: 'name', order: 'asc' }})).data
    console.log(files)
    const fileId = files.find(temp => returnPath.includes(temp.name)).id

    fileUploadFormData.value.object = fileId
    fileUploadFormData.value.path = returnPath
    console.log(fileUploadFormData.value)

    const {data,error} = await supabase
        .from("documents")
        .insert([fileUploadFormData.value])
        .select()
    console.log(data)
    console.log(error)
  }

  uploadModalOpen.value = false;
}



const changeFolder = async () => {
  console.log("Change Folder")
  console.log(selectedDocument.value.path)

  let filename = selectedDocument.value.path.split("/")[2]
  let newPath = `${user.value.app_metadata.tenant}/${newFolder.value}/${filename}`
  console.log(newPath)

  const { data, error } = await supabase
      .storage
      .from('documents')
      .move(selectedDocument.value.path, newPath )

  console.log(data)
  console.log(error)

}

const newFolder = ref("")

const selectedDocument = ref({})
const showDocumentModal = ref(false)

const openDocument = async (document) => {
  console.log("open")
  selectedDocument.value = document
  showDocumentModal.value = true

}
</script>

<style scoped>
.documentList {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  height: 85vh;
  overflow-y: scroll;
}

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

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

.previewEmbed {
  width: 100%;
  height: 22vh;
  overflow: hidden;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

.previewEmbed::-webkit-scrollbar {
  display: none;
}

.bigPreview {
  height: 70vh;
  width: 100%;
}
</style>