<template>
  <div class="auto-grid" style="--min: 15rem; --gap: 0.5rem">
    <FileUpload
      mode="basic"
      name="images[]"
      @change="addImages($event)"
      :auto="true"
      :multiple="true"
      accept="image/*"
      :maxFileSize="1000000"
      invalidFileSizeMessage="Fichier trop lourd"
      chooseLabel="Ajouter une ou plusieurs images"
      class="flex flex-col justify-center | bg-white | border border-grey-200 | text-grey-800 | font-medium | rounded-xl"
      ref="uploadBtn"
    >
      <template #chooseicon>
        <svg
          width="20"
          height="20"
          viewBox="0 0 20 20"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M0.714355 15.0001V16.4286C0.714355 17.1864 1.01538 17.9131 1.55119 18.4489C2.08701 18.9848 2.81374 19.2858 3.5715 19.2858H16.4286C17.1864 19.2858 17.9131 18.9848 18.4489 18.4489C18.9848 17.9131 19.2858 17.1864 19.2858 16.4286V15.0001M5.71436 5.71436L10.0001 0.714355M10.0001 0.714355L14.2858 5.71436M10.0001 0.714355V13.5715"
            stroke="currentColor"
            stroke-width="1.25"
            stroke-linecap="round"
            stroke-linejoin="round"
          />
        </svg>
      </template>
      <template
        #content="{
          files,
          uploadedFiles,
          removeUploadedFileCallback,
          removeFileCallback,
        }"
      >
        <div v-if="files.length > 0">Fichiers importés</div>
      </template>
    </FileUpload>
    <figure v-for="image in tab.images" class="image">
      <img
        :src="image.url"
        alt=""
        @click="ArrayUtils.toggle(tab.selectedImages, image)"
      />
    </figure>
    <Toast />
  </div>
</template>

<script setup>
import { usePageStore } from "../../../../stores/page";
import Toast from "primevue/toast";
import { useToast } from "primevue/usetoast";
import FileUpload from "primevue/fileupload";
import { storeToRefs } from "pinia";
import { computed, ref } from "vue";
import { useAddImagesModalStore } from "../../../../stores/addImagesModal";
import ArrayUtils from "../../../../utils/array";

const { page } = storeToRefs(usePageStore());
const toast = useToast();

const emit = defineEmits(["add-images"]);
const uploadBtn = ref(null);

const { tabs } = storeToRefs(useAddImagesModalStore());

const tab = computed(() => {
  return tabs.value.find((tab) => tab.id === "my-images");
});

function addImages() {
  const newImages = uploadBtn.value.files.map((file) => {
    return {
      url: URL.createObjectURL(file),
      description: "",
      tags: [],
      name: file.name,
    };
  });
  tab.value.images = [...tab.value.images, ...newImages];
  tab.value.selectedImages = [...tab.value.selectedImages, ...newImages];
}
</script>
