<script setup >

const props = defineProps({
  type: {
    type: String
  },
  elementId: {
    type: String
  }
})

const {type, elementId} = props

const emit = defineEmits(["uploadFinished"])

const dataStore = useDataStore()
const profileStore = useProfileStore()

const uploadModalOpen = ref(false)
const uploadInProgress = ref(false)
const fileUploadFormData = ref({
  project: null,
  tenant: profileStore.currentTenant
})
const availableTags = ref([])
const selectedTags = ref([])
const setup = async () => {
  availableTags.value = await useSupabaseSelect("filetags")
}

setup()


const openModal = () => {
  uploadModalOpen.value = true
}

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

  let fileData = fileUploadFormData.value
  fileData[type] = elementId

  await useFiles().uploadFiles(fileData,  document.getElementById("fileUploadInput").files,selectedTags.value,true)

  uploadModalOpen.value = false;
  uploadInProgress.value = false;
  emit("uploadFinished")
}
</script>

<template>
  <USlideover
      v-model="uploadModalOpen"
  >
    <UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }" class="h-full">
      <template #header>
        <div class="flex items-center justify-between">
          <h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
            Datei hochladen
          </h3>
          <UButton
              color="gray"
              variant="ghost"
              icon="i-heroicons-x-mark-20-solid"
              class="-my-1"
              @click="uploadModalOpen = false"
              :disabled="uploadInProgress"
          />
        </div>
      </template>

      <UFormGroup
          label="Datei:"
      >
        <UInput
            type="file"
            id="fileUploadInput"
            multiple
            accept="image/jpeg, image/png, image/gif, application/pdf"
        />
      </UFormGroup>
      <UFormGroup
          label="Tags:"
          class="mt-3"
      >
        <USelectMenu
            multiple
            option-attribute="name"
            value-attribute="id"
            searchable
            searchable-placeholder="Suchen..."
            :options="availableTags"
            v-model="selectedTags"
        >
          <template #label>
            <span v-if="selectedTags.length > 0">{{selectedTags.map(i => availableTags.find(x => x.id === i).name).join(", ")}}</span>
            <span v-else>Keine Tags ausgewählt</span>
          </template>
        </USelectMenu>
      </UFormGroup>

      <template #footer>
        <UButton
            @click="uploadFiles"
            :loading="uploadInProgress"
        >Hochladen</UButton>
      </template>

    </UCard>
  </USlideover>

  <UButton
      @click="openModal"
      icon="i-heroicons-arrow-up-tray"
  >
    Hochladen
  </UButton>
</template>

<style scoped>

</style>