<script setup>


import {BlobReader, BlobWriter, ZipWriter} from "@zip.js/zip.js";
import {useSupabaseSelectSingle} from "~/composables/useSupabase.js";
import DocumentDisplayModal from "~/components/DocumentDisplayModal.vue";
import DocumentUploadModal from "~/components/DocumentUploadModal.vue";
import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  /*'/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },*/
  '+': () => {
    //Hochladen
    uploadModalOpen.value = true
  },
  'Enter': {
    usingInput: true,
    handler: () => {
      let entry = renderedFileList.value[selectedFileIndex.value]

      if(entry.type === "file") {
        showFile(entry.id)
        console.log(entry)
      } else {
        changeFolder(currentFolders.value.find(i => i.id === entry.id))
      }

    }
  },
  'arrowdown': () => {
    if(selectedFileIndex.value < renderedFileList.value.length - 1) {
      selectedFileIndex.value += 1
    } else {
      selectedFileIndex.value = 0
    }
  },
  'arrowup': () => {
    if(selectedFileIndex.value === 0) {
      selectedFileIndex.value = renderedFileList.value.length - 1
    } else {
      selectedFileIndex.value -= 1
    }
  }
})

const dataStore = useDataStore()
const profileStore = useProfileStore()
const supabase = useSupabaseClient()
const router = useRouter()
const route = useRoute()
const slideover = useSlideover()
const modal = useModal()

dataStore.fetchDocuments()

const uploadModalOpen = ref(false)
const createFolderModalOpen = ref(false)
const uploadInProgress = ref(false)
const fileUploadFormData = ref({
  tags: ["Eingang"],
  path: "",
  tenant: profileStore.currentTenant,
  folder: null
})

const files = useFiles()

let tags = dataStore.getDocumentTags

const displayMode = ref("list")
const displayModes = ref([{label: 'Liste',key:'list', icon: 'i-heroicons-list-bullet'},{label: 'Kacheln',key:'rectangles', icon: 'i-heroicons-squares-2x2'}])



const documents = ref([])
const folders = ref([])
const filetags = ref([])

const currentFolder = ref(null)

const loadingDocs = ref(false)
const isDragTarget = ref(false)
const setupPage = async () => {
  folders.value = await useSupabaseSelect("folders")

  documents.value = await files.selectDocuments()

  filetags.value = await useSupabaseSelect("filetags")

  if(route.query) {
    if(route.query.folder) {
      currentFolder.value = await useSupabaseSelectSingle("folders", route.query.folder)
    }
  }


  const dropZone = document.getElementById("drop_zone")
  dropZone.ondragover = function (event) {
    console.log(event)
    isDragTarget.value = true
    event.preventDefault()
  }

  dropZone.ondragleave = function (event) {
    isDragTarget.value = false
  }

  dropZone.ondrop = async function (event) {
    console.log("files dropped")
    event.preventDefault()

    await uploadFiles(event.dataTransfer.files)
    isDragTarget.value = false
    setupPage()
  }


  loadingDocs.value = false

}
setupPage()
const currentFolders = computed(() => {
  if(folders.value.length > 0) {

    let tempFolders = folders.value.filter(i => currentFolder.value ? i.parent === currentFolder.value.id : !i.parent)

    return tempFolders
  } else return []

})

const breadcrumbLinks = computed(() => {

  if(currentFolder.value) {
    let parents = []

    const addParent = (parent) => {
      parents.push(parent)
      if(parent.parent) {
        addParent(folders.value.find(i => i.id === parent.parent))
      }
    }

    if(currentFolder.value.parent) {
      addParent(folders.value.find(i => i.id === currentFolder.value.parent))
    }

    return [{
      label: "Home",
      click: () => {
        changeFolder(null)
      },
      icon: "i-heroicons-folder"
    },
    ...parents.map(i => {
      return {
        label: folders.value.find(x => x.id === i.id).name,
        click: () => {
          changeFolder(i)
        },
        icon: "i-heroicons-folder"
      }
    }).reverse(),
    {
      label: currentFolder.value.name,
      click: () => {
        changeFolder(currentFolder.value)
      },
      icon: "i-heroicons-folder"
    }]

  } else {
    return [{
      label: "Home",
      click: () => {
        changeFolder(null)
      },
      icon: "i-heroicons-folder"
    }]
  }
})

const filteredDocuments = computed(() => {

  return documents.value.filter(i => currentFolder.value ? i.folder === currentFolder.value.id : !i.folder)

})

const changeFolder = async (newFolder) => {
  loadingDocs.value = true
  currentFolder.value = newFolder

  if(newFolder) {
    fileUploadFormData.value.folder = newFolder.id
    await router.push(`/files?folder=${newFolder.id}`)
  } else {
    fileUploadFormData.value.folder = null
    await router.push(`/files`)
  }

  setupPage()
}

const createFolderData = ref({})
const createFolder = async () => {
  const {data,error} = await supabase
      .from("folders")
      .insert({
        tenant: profileStore.currentTenant,
        parent: currentFolder.value ? currentFolder.value.id : undefined,
        name: createFolderData.value.name,

      })

  createFolderModalOpen.value = false

  setupPage()

}

const uploadFiles = async (files) => {
  uploadInProgress.value = true;

  if(files) {
    //await dataStore.uploadFiles({tags: ["Ablage"],tenant: profileStore.currentTenant,folder: currentFolder.value.id}, files, true)
    await dataStore.uploadFiles({tags: ["Ablage"],tenant: profileStore.currentTenant}, files, true)

  } else {
    await dataStore.uploadFiles(fileUploadFormData.value, document.getElementById("fileUploadInput").files, true)

  }


  uploadModalOpen.value = false;
  uploadInProgress.value = false;
}

const downloadSelected = async () => {
  const bucket = "files";

  let files = []
  dataStore.documents.filter(doc => doc.selected).forEach(doc => files.push(doc.path))

  console.log(files)

  // If there are no files in the folder, throw an error
  if (!files || !files.length) {
    throw new Error("No files to download");
  }

  const promises = [];

// Download each file in the folder
  files.forEach((file) => {
    promises.push(
        supabase.storage.from(bucket).download(`${file}`)
    );
  });

// Wait for all the files to download
  const response = await Promise.allSettled(promises);

// Map the response to an array of objects containing the file name and blob
  const downloadedFiles = response.map((result, index) => {
    if (result.status === "fulfilled") {

      console.log(files[index].split("/")[files[index].split("/").length -1])

      return {
        name: files[index].split("/")[files[index].split("/").length -1],
        blob: result.value.data,
      };
    }
  });

// Create a new zip file
  const zipFileWriter = new BlobWriter("application/zip");
  const zipWriter = new ZipWriter(zipFileWriter, { bufferedWrite: true });

// Add each file to the zip file
  downloadedFiles.forEach((downloadedFile) => {
    if (downloadedFile) {
      zipWriter.add(downloadedFile.name, new BlobReader(downloadedFile.blob));
    }
  });

// Download the zip file
  const url = URL.createObjectURL(await zipWriter.close());
  const link = document.createElement("a");

  link.href = url;
  link.setAttribute("download", "documents.zip");

  document.body.appendChild(link);

  link.click();
}

const renderedFileList = computed(() => {
    let files = filteredDocuments.value.map(i => {
      return {
        label: i.path.split("/")[i.path.split("/").length -1],
        id: i.id,
        type: "file"
      }
    })

    let folders = currentFolders.value.map(i => {
      return {
        label: i.name,
        id: i.id,
        type: "folder"
      }
    })

    return [...folders,...files]

})
const selectedFileIndex = ref(0)

const showFile = (fileId) => {
  console.log(fileId)
  modal.open(DocumentDisplayModal,{
    documentData: documents.value.find(i => i.id === fileId),
  })
}



</script>

<template>

  <UDashboardNavbar
      title="Dateien"
  >

  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <UBreadcrumb
          :links="breadcrumbLinks"
      />
    </template>
    <template #right>
      <USelectMenu
        :options="displayModes"
        value-attribute="key"
        option-attribute="label"
        v-model="displayMode"
        :ui-menu="{ width: 'min-w-max'}"
      >
        <template #label>
          <UIcon class="w-5 h-5" :name="displayModes.find(i => i.key === displayMode).icon"/>
        </template>
      </USelectMenu>

      <UButton @click="modal.open(DocumentUploadModal,{fileData: {folder: currentFolder.id}})">+ Datei</UButton>
      <UButton
          @click="createFolderModalOpen = true"
          variant="outline"
      >+ Ordner</UButton>
      <UModal
          v-model="createFolderModalOpen"
      >
        <UCard>
          <template #header>
            Ordner Erstellen
          </template>



          <UFormGroup
              label="Ordner erstellen"
          >
            <UInput
                v-model="createFolderData.name"
            />
          </UFormGroup>

          <template #footer>
            <UButton
              @click="createFolder"
            >
              Erstellen
            </UButton>
          </template>
        </UCard>

      </UModal>

    </template>
  </UDashboardToolbar>
  <div id="drop_zone" class="h-full scrollList">
    <UDashboardPanelContent v-if="!isDragTarget" >
      <div v-if="displayMode === 'list'">
        <table class="w-full">
          <thead>
            <tr>
              <td class="font-bold">Name</td>
              <td class="font-bold">Erstellt am</td>
            </tr>
          </thead>
          <tr v-for="(entry,index) in renderedFileList">
            <td>
              <UIcon class="mr-1" :name="entry.type === 'folder' ? 'i-heroicons-folder' : 'i-heroicons-document'"/>
              <a
                  style="cursor: pointer"
                  :class="[...index === selectedFileIndex ? ['text-primary', 'text-xl'] : ['dark:text-white','text-black','text-xl']]"
                  @click="entry.type === 'folder' ? changeFolder(currentFolders.find(i => i.id === entry.id)) : showFile(entry.id)"
              >{{entry.label}}</a>

            </td>
            <td>
              <span v-if="entry.type === 'file'" class="text-xl">{{dayjs(documents.find(i => i.id === entry.id).created_at).format("DD.MM.YY HH:mm")}}</span>
              <span v-if="entry.type === 'folder'" class="text-xl">{{dayjs(currentFolders.find(i => i.id === entry.id).created_at).format("DD.MM.YY HH:mm")}}</span>
            </td>
          </tr>
        </table>
      </div>
      <div v-else-if="displayMode === 'rectangles'">
        <div class="flex flex-row w-full flex-wrap" v-if="currentFolders.length > 0">
          <a
              class="w-1/6 folderIcon flex flex-col p-5 m-2"
              v-for="folder in currentFolders"
              @click="changeFolder(folder)"
          >

            <UIcon
                name="i-heroicons-folder"
                class="w-20 h-20"
            />
            <span class="text-center truncate">{{folder.name}}</span>
          </a>
        </div>

        <UDivider class="my-5" v-if="currentFolder">{{currentFolder.name}}</UDivider>
        <UDivider class="my-5" v-else>Ablage</UDivider>

        <div v-if="!loadingDocs">
          <DocumentList
              v-if="filteredDocuments.length > 0"
              :documents="filteredDocuments"
              @selectDocument="(info) => console.log(info)"
          />
          <UAlert
              v-else
              class="mt-5 w-1/2 mx-auto"
              icon="i-heroicons-light-bulb"
              title="Keine Dokumente vorhanden"
              color="primary"
              variant="outline"
          />
        </div>
        <UProgress
            animation="carousel"
            v-else
            class="w-2/3 my-5 mx-auto"
        />
      </div>
    </UDashboardPanelContent>
    <UCard
        class=" m-5"
        v-else>
      <template #header>
        <p class="mx-auto">Dateien zum hochladen hierher ziehen</p>

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




  <USlideover
      v-model="uploadModalOpen"
  >

    <UCard class="flex flex-col flex-1" :ui="{ body: { base: 'flex-1' }, ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
      <template #header>
        Datei Hochladen
      </template>

      <div class="h-full">
        <UFormGroup
            label="Datei:"
        >
          <UInput
              type="file"
              id="fileUploadInput"
              multiple
          />
        </UFormGroup>

        <UFormGroup
            label="Tags:"
            class="mt-3"
        >
          <USelectMenu
              multiple
              searchable
              searchable-placeholder="Suchen..."
              option-attribute="name"
              value-attribute="id"
              :options="filetags"
              v-model="fileUploadFormData.tags"
          />
        </UFormGroup>
      </div>

      <template #footer>
        <UButton
            v-if="!uploadInProgress"
            class="mt-3"
            @click="uploadFiles"
        >Hochladen</UButton>
        <UProgress
            v-else
            animation="carousel"
        />
      </template>
    </UCard>
  </USlideover>
</template>

<style scoped>
.folderIcon {
  border: 1px solid lightgrey;
  border-radius: 10px;
  color: dimgrey;
}

.folderIcon:hover {
  border: 1px solid #69c350;
  color: #69c350;
}

tr:nth-child(odd) {
  background-color: rgba(0, 0, 0, 0.05);
}

</style>