<script setup>

const toast = useToast()
const supabase = useSupabaseClient()
const router = useRouter()
const props = defineProps({
  document: {
    type: Object,
    required: true
  },
  openShowModal: {
    type: Boolean,
    required: false,
  }
})

const {document, openShowModal:openShowModalProp } = props;
const {fetchDocuments, getDocumentTags, fetchVendorInvoices} = useDataStore()
const {projects, customers} = storeToRefs(useDataStore())
const tags = getDocumentTags
const openShowModal = ref(false)

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

/*const uploadFiles = async () => {
  const uploadSingleFile = async (file) => {

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

    if (error) {
      console.log(error)
    } else if (data) {
      const returnPath = data.path

      if (error) {

      } else {
        const files = (await supabase.storage.from('files').list(`${user.value.app_metadata.tenant}/`, {
          limit: 100,
          offset: 0,
          sortBy: {column: 'name', order: 'asc'}
        })).data

        fileUploadFormData.value.path = returnPath

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

  uploadInProgress.value = true

  let files = document.getElementById("fileUploadInput").files

  if(files.length === 1) {
    await uploadSingleFile(files[0])
  } else if( files.length > 1) {

    for(let i = 0; i < files.length; i++){
      uploadSingleFile(files[i])
    }

  }

  uploadModalOpen.value = false;
  uploadInProgress.value = false;
  fetchDocuments()
}*/


const updateDocument = async () => {


  let objData = document
  delete objData.url

  const {data,error} = await supabase
      .from("documents")
      .update(objData)
      .eq('id',objData.id)
      .select()

  if(error) {
    console.log(error)
  } else {
    toast.add({title: "Dokument aktualisiert"})
    fetchDocuments()
    openShowModal.value = false
  }

}

const createVendorInvoice = async () => {
  const {data,error} = await supabase
      .from("vendorInvoices")
      .insert([{
        document: document.id,
      }])
      .select()
  if(error) {
    console.log(error)
  } else if(data) {
    fetchVendorInvoices()
    await router.push("/vendorinvoices")
  }

}
</script>

<template>
  <div class="documentListItem">
    <embed
        :src="document.url"
        class="previewEmbed"
    />
    <UButton
        @click="openDocument"
        class="mt-3"
    >
      <UIcon name="i-heroicons-eye-solid" />
    </UButton>
    <UToggle
        v-model="document.selected"
        class="ml-2"
    />
  </div>



  <!-- Slideovers  -->

  <USlideover
      v-model="openShowModal"
      fullscreen
  >
    <UCard class="h-full">
      <embed
          class="bigPreview mb-3"
          :src="document.url"
      />

      <div class="flex items-center gap-2">
        <UBadge
            v-for="tag in document.tags"
        >
          {{tag}}
        </UBadge>
      </div>





      <UFormGroup
          label="Tags ändern:"
      >
        <USelectMenu
            :options="tags"
            v-model="document.tags"
            @close="updateDocument"
            multiple
        />
      </UFormGroup>

      <UFormGroup
          label="Projekt zuweisen:"
      >
        <USelectMenu
            :options="projects"
            option-attribute="name"
            value-attribute="id"
            v-model="document.project"
            @change="updateDocument"
            searchable
            :search-attributes="['name']"
        >
          <template #label>
            {{projects.find(item => item.id === document.project) ? projects.find(item => item.id === document.project).name : document.project }}
          </template>
        </USelectMenu>
      </UFormGroup>

      <UFormGroup
          label="Kunde zuweisen:"
      >
        <USelectMenu
            :options="customers"
            option-attribute="name"
            value-attribute="id"
            v-model="document.customer"
            @change="updateDocument"
            searchable
            :search-attributes="['name']"
        >
          <template #label>
            {{customers.find(item => item.id === document.customer) ? customers.find(item => item.id === document.customer).name : document.customer }}
          </template>
        </USelectMenu>
      </UFormGroup>

      <UButton
        v-if="document.tags.includes('Eingangsrechnung')"
        @click="createVendorInvoice"
      >
        Eingangsrechnung erstellen
      </UButton>


    </UCard>
  </USlideover>
</template>

<style scoped>
.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>