<template>
  <Dialog
    v-model:visible="isOpen"
    id="image-details"
    modal
    header="Détails de l’image"
    class="bg-white | text-grey-800 | rounded-2xl | overflow-hidden"
  >
    <picture :style="'--image: url('+image.url+')'">
      <img :src="image.url" alt="" class="bg-grey-200 w-full" loading="lazy">
    </picture>
    <div class="flex flex-col | p-32" style="--row-gap: var(--space-32)">
      <fieldset class="image__tags">
        <legend class="text-sm text-grey-700 | mb-8">Tags</legend>
        <div class="flex" style="gap: var(--space-8)">
          <template v-for="(pageTag, index) in page.tags" :key="index">
            <input
              class="sr-only"
              type="checkbox"
              :id="pageTag + '-image'"
              :name="pageTag + '-image'"
              :value="pageTag"
              @change="saveTags()"
              v-model="image.tags"
            />
            <label class="btn btn--sm btn--primary" :for="pageTag + '-image'">{{
              StringUtils.toPascalCase(pageTag)
            }}</label>
          </template>
        </div>
      </fieldset>
      <div class="image__description | w-full">
        <label
          for="image-description"
          class="flex | text-sm text-grey-700 | mb-8"
          >Description de l’image</label
        >
        <textarea
          name="image-description"
          id="image-description"
          placeholder="Ajoutez une description à l’image…"
          class="border border-grey-200 | rounded-xl | p-16 | w-full"
          v-model="image.description"
          @input="saveDescription()"
        ></textarea>
      </div>
      <button
        data-icon="delete"
        class="btn btn--black-10 | ml-auto mt-auto"
        @click="remove()"
      >
        Supprimer cette image
      </button>
    </div>
  </Dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import { usePageStore } from "../../../stores/page";
import StringUtils from "../../../utils/string";
import Dialog from "primevue/dialog";
import debounce from "lodash/debounce";

const { imageDetails } = defineProps({
  imageDetails: Object,
});

const emit = defineEmits(["close", "remove"]);

const isOpen = ref(true);
watch(isOpen, () => {
  emit("close");
});

const { page } = usePageStore();

const image = ref(imageDetails);

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

function remove() {
  const headers = {
    method: "POST",
    body: JSON.stringify({
      pageUri: page.uri,
      fileName: image.value.name,
    }),
  };
  fetch("/remove-file.json", headers)
    .then((res) => res.json())
    .then((json) => {
      console.log(json);
      emit("remove", image.value);
      isOpen.value = false;
    })
    .catch((error) => {
      console.error("Erreur lors de la suppression :", error);
    });
}
</script>

<style>
#image-details {
  width: min(100vw - var(--gutter) * 2, 70rem);
  height: min(100vh - var(--gutter) * 2, 50rem);
  flex-direction: row !important;
}
#image-details [data-pc-section="header"] {
  position: absolute;
  width: 100%;
  max-width: min(480px, 50%);
  right: 0;
  z-index: 1102;
  padding: 1.5rem var(--space-32);
  height: auto;
  background: var(--color-background);
}
#image-details [data-pc-section="content"] {
  display: flex;
}
#image-details [data-pc-section="content"] img {
  object-fit: contain;
  max-height: 100%;
  z-index: 1;
}
#image-details [data-pc-section="content"] picture {
  position: relative;
  display: grid;
  place-items: center;
  overflow: hidden;
  flex-grow: 1;
}
#image-details [data-pc-section="content"] picture::before {
  content: '';
  position: absolute;
  inset: -3rem;
  background-image: var(--image);
  background-repeat: no-repeat;
  background-size: cover;
  filter: blur(3rem);
  opacity: .4;
}
#image-details [data-pc-section="content"] > * {
  width: 50%;
}
#image-details [data-pc-section="content"] > div {
  padding-top: 5rem;
  overflow-y: auto;
  max-width: 480px;
}
@media (max-width: 767px) {
  #image-details [data-pc-section="content"] {
    flex-direction: column;
  }
  #image-details [data-pc-section="header"] {
    top: 50%;
    left: 0;
    max-width: 100%;
  }
  #image-details [data-pc-section="content"] > * {
    width: 100%;
    height: 50%;
  }
  #image-details [data-pc-section="content"] > div {
    max-width: 100%;
  }
}
</style>
