<template>
  <div
    class="flex flex-col items-start | bg-grey-50 | rounded-2xl | w-full | p-8"
  >
    <Accordion
      value="0"
      class="flex flex-col | w-full"
      style="--row-gap: var(--space-8)"
    >
      <AccordionPanel
        v-for="(image, index) in images"
        :key="index + 1"
        :value="index"
        class="w-full | bg-white | rounded-xl | p-12 pt-8"
      >
        <AccordionHeader>
          <span class="badge">{{ index + 1 }}</span>
        </AccordionHeader>
        <AccordionContent>
          <div class="image-details__description | my-16">
            <label
              for="image-description"
              class="flex | text-sm text-grey-700 | mb-8"
              >Description</label
            >
            <textarea
              name="image-description"
              id="image-description"
              :placeholder="t('forms.imageDescriptionPlaceholder')"
              rows="3"
              class="border border-grey-200 | rounded-xl | p-16 | w-full"
              v-model="image.description"
            ></textarea>
          </div>
          <fieldset class="image-details__filters | flex-1">
            <legend class="text-sm text-grey-700 | mb-8">
              {{ t('forms.selectTags') }}
            </legend>
            <div class="flex" style="gap: var(--space-8)">
              <template v-for="tag in page.tags" :key="tag">
                <input
                  class="sr-only"
                  type="checkbox"
                  :id="`${tag}-image-edit`"
                  :name="`${tag}-image-edit`"
                  :value="`${tag}`"
                  v-model="image.tags"
                />
                <label
                  class="btn btn--sm btn--primary"
                  :for="`${tag}-image-edit`"
                  >{{ StringUtils.toPascalCase(tag) }}</label
                >
              </template>
            </div>
          </fieldset>
        </AccordionContent>
      </AccordionPanel>
      <template #collapseicon>
        <svg
          aria-hidden="true"
          width="20"
          height="20"
          viewBox="0 0 20 20"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
          style="transform: rotate(180deg)"
        >
          <path
            d="M1.875 6.0625L9.5625 13.75C9.61861 13.8098 9.68638 13.8574 9.76163 13.89C9.83688 13.9226 9.918 13.9394 10 13.9394C10.082 13.9394 10.1631 13.9226 10.2384 13.89C10.3136 13.8574 10.3814 13.8098 10.4375 13.75L18.125 6.0625"
            stroke="#5E6060"
            stroke-width="1.25"
            stroke-linecap="round"
            stroke-linejoin="round"
          />
        </svg>
      </template>
      <template #expandicon>
        <svg
          aria-hidden="true"
          width="20"
          height="20"
          viewBox="0 0 20 20"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M1.875 6.0625L9.5625 13.75C9.61861 13.8098 9.68638 13.8574 9.76163 13.89C9.83688 13.9226 9.918 13.9394 10 13.9394C10.082 13.9394 10.1631 13.9226 10.2384 13.89C10.3136 13.8574 10.3814 13.8098 10.4375 13.75L18.125 6.0625"
            stroke="#5E6060"
            stroke-width="1.25"
            stroke-linecap="round"
            stroke-linejoin="round"
          />
        </svg>
      </template>
    </Accordion>
    <button class="btn | w-full | mt-auto" @click="addImagesToBrief()">
      {{ t('buttons.addSelectedImages') }}
    </button>
  </div>
</template>
<script setup>
import Accordion from "primevue/accordion";
import AccordionPanel from "primevue/accordionpanel";
import AccordionHeader from "primevue/accordionheader";
import AccordionContent from "primevue/accordioncontent";
import { usePageStore } from "../../../../stores/page";
import StringUtils from "../../../../utils/string";
import { storeToRefs } from "pinia";
import { useAddImagesModalStore } from "../../../../stores/addImagesModal";
import { computed } from "vue";
import { useI18n } from "vue-i18n";

const { page } = storeToRefs(usePageStore());
const { t } = useI18n();

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

const emit = defineEmits("close");

const images = computed(() => {
  return activeTab.value.selectedImages;
});

// function saveTags(image) {
//   const headers = {
//     method: "POST",
//     body: JSON.stringify({
//       pageUri: page.value.uri,
//       fileName: image.name,
//       properties: [
//         {
//           name: "tags",
//           value: image.tags,
//         },
//       ],
//     }),
//   };
//   fetch("/save-file.json", headers)
//     .then((res) => res.json())
//     .then((json) => {
//       console.log(json);
//     })
//     .catch((error) => {
//       console.error("Erreur lors de la sauvegarde :", error);
//     });
// }

// const saveDescription = debounce((image) => {
//   const headers = {
//     method: "POST",
//     body: JSON.stringify({
//       pageUri: page.value.uri,
//       fileName: image.name,
//       properties: [
//         {
//           name: "description",
//           value: image.description,
//         },
//       ],
//     }),
//   };
//   fetch("/save-file.json", headers)
//     .then((res) => res.json())
//     .then((json) => {
//       console.log(json);
//     })
//     .catch((error) => {
//       console.error("Erreur lors de la sauvegarde :", error);
//     });
// }, 1000);

function addImagesToBrief() {
  const formData = new FormData();

  const blobPromises = images.value.map((item, index) => {
    if (item.url.startsWith("blob:")) {
      return fetch(item.url)
        .then((response) => response.blob())
        .then((blob) => {
          formData.append("images[]", blob, item.name);
          formData.append(
            `imagesMeta[${index}][description]`,
            item.description
          );
          formData.append(
            `imagesMeta[${index}][tags]`,
            JSON.stringify(item.tags)
          );
        });
    } else {
      formData.append("imageUris[]", JSON.stringify(item));
      return Promise.resolve();
    }
  });

  Promise.all(blobPromises).then(() => {
    fetch("/upload-images.json?pageUri=" + page.value.uri, {
      method: "POST",
      body: formData,
    })
      .then((res) => res.json())
      .then((json) => {
        page.value.moodboard = json.images;
        emit("close");
      })
      .catch((error) => console.error("Error:", error));
  });
}
</script>

<style>
/* Accordion */
[data-pc-name="accordionheader"] {
  height: var(--space-40);
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
