<template>
  <header
    class="project-details | flex items-start | bg-white | rounded-2xl | p-16 | w-full"
  >
    <div class="project-details__description | flex-1">
      <label
        for="project-description"
        class="flex | text-sm text-grey-700 | mb-8"
        >Description du projet</label
      >
      <textarea
        name="project-description"
        id="project-description"
        placeholder="Ajoutez une description générale de votre projet…"
        rows="2"
        class="border border-grey-200 | rounded-xl | p-16 | w-full"
        v-model="page.content.description"
        @input="saveDescription()"
      ></textarea>
    </div>
    <fieldset class="project-details__filters | flex-1">
      <legend class="text-sm text-grey-700 | mb-8">Filtrer par tags</legend>
      <div class="flex" style="gap: var(--space-8)">
        <button
          class="btn btn--sm btn--grey"
          id="all"
          :aria-pressed="selectedTags.length === 0"
          role="switch"
          @click="clearTags()"
        >
          Voir tout
        </button>
        <template v-for="tag in page.tags" :key="tag">
          <input
            class="sr-only"
            type="checkbox"
            :id="`${tag}`"
            :name="`${tag}`"
            :value="`${tag}`"
            v-model="localSelectedTags"
          />
          <label class="btn btn--sm btn--primary" :for="`${tag}`">{{
            tag
          }}</label>
        </template>
      </div>
    </fieldset>
  </header>
</template>

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

const { selectedTags } = defineProps({
  selectedTags: Array,
});

const { page } = usePageStore();
const emit = defineEmits(["update:selectedTags"]);

const localSelectedTags = ref([...selectedTags]);

watch(localSelectedTags, updateSelectedTags);

function updateSelectedTags(tags) {
  emit("update:selectedTags", tags);
}

const isWaitingForSave = ref(false);

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

function clearTags() {
  localSelectedTags.value = [];
}
</script>
