<template>
  <aside id="comments-container" aria-labelledby="comments-label">
    <h2 id="comments-label" class="sr-only">Commentaires</h2>
    <div class="comments | flow">
      <template v-if="!openedComment">
        <!-- TODO: faire un composant comment -->
        <article
          v-for="(comment, commentIndex) in Object.values(comments).reverse()"
          :key="commentIndex"
          class="comment | flow"
          :data-status="setStatus(comment)"
          @click="open(comment)"
        >
          <header>
            <p>
              <strong>{{ comment.user.name ?? comment.user.email }}</strong>
              <span class="comment__id">#{{ commentIndex + 1 }}</span> •
              <span class="comment__page">Page {{ pageIndex }}</span>
              <time :datetime="dayjs(comment.date).format('YYYY-MM-DD')">{{
                formatDate(comment.date)
              }}</time>
            </p>
          </header>
          <p class="comment__body">
            {{ comment.text }}
          </p>
          <!-- TODO: à dynamiser (affichage ou non si replies + nombre de replies)-->
          <footer class="comment__replies">
            <span>1 réponse</span>
          </footer>
        </article>
      </template>
      <template v-else>
        <!-- TODO: mettre la bonne cible pour to: -->
        <router-link
          :to="'/' + page.parent"
          class="btn | justify-start w-full | bg-white-10 text-white | px-8"
          data-icon="chevron-single-left"
        >
          <span>Retour à la liste</span>
        </router-link>
        <!-- TODO: utiliser le composant comment ici -->
        <article 
          class="comment"
          data-opened="true"
        >
          <header>
            <p>
              <strong>{{ openedComment.user.name ?? openedComment.user.email }}</strong>
              <span class="comment__id">#{{ commentIndex + 1 }}</span> •
              <span class="comment__page">Page {{ pageIndex }}</span>
              <time :datetime="dayjs(openedComment.date).format('YYYY-MM-DD')">{{
                formatDate(openedComment.date)
              }}</time>
            </p>
          </header>
          <p class="comment__body">
            {{ openedComment.text }}
          </p>
          <footer class="comment__replies">
            <span>1 réponse</span>
          </footer>
        </article>
        <div class="replies">
          <!-- TODO: utiliser le composant comment ici -->
          <article 
            v-for="comment in openedComment.replies"
            class="comment reply"
          >
            <header>
              <p>
                <strong>{{ comment.user.name ?? comment.user.email }}</strong>
                <span class="comment__id">#{{ commentIndex + 1 }}</span> •
                <span class="comment__page">Page {{ pageIndex }}</span>
                <time :datetime="dayjs(comment.date).format('YYYY-MM-DD')">{{
                  formatDate(comment.date)
                }}</time>
              </p>
            </header>
            <p class="comment__body">
              {{ comment.text }}
            </p>
          </article>
        </div>
      </template>
    </div>
    <button
      v-if="!openedComment && !isAddOpen"
      id="create-comment"
      class="btn btn--white-20 | w-full"
      @click="isAddOpen = true"
    >
      Ajouter un commentaire
    </button>
    <button
      v-if="openedComment && !isReplyOpen"
      id="reply-comment"
      class="btn btn--white-20 | justify-start w-full | text-white-50"
      @click="isReplyOpen = true"
    >
      Répondre…
    </button>

    <form
      v-if="isAddOpen"
      action=""
      method="post"
      class="flow | bg-white-20 | p-12 | rounded-xl"
      @submit="addComment"
    >
      <label class="sr-only" for="comment">Votre commentaire</label>
      <textarea
        name="comment"
        id="comment"
        placeholder="Ajouter un commentaire…"
        rows="5"
        class="text-sm | rounded-lg bg-black p-12"
        v-model="newCommentText"
      ></textarea>
      <footer class="flex">
        <input type="submit" class="btn btn--tranparent" />
        <button class="btn btn--white-10" @click="closeAddField()">
          Annuler
        </button>
      </footer>
    </form>
  </aside>
</template>

<script setup>
import dayjs from "dayjs";
import "dayjs/locale/fr";
import uniqid from "uniqid";
import { ref } from "vue";
import { useUserStore } from "../../stores/user";
import { usePageStore } from "../../stores/page";
import { useApiStore } from "../../stores/api";

dayjs.locale("fr");

const { currentPageIndex, file, comments } = defineProps({
  currentPageIndex: Number,
  file: Object,
  comments: Object,
});

const { user } = useUserStore();
const { page } = usePageStore();
const api = useApiStore();

const openedComment = ref(null);

const newCommentText = ref("");
const isAddOpen = ref(false);
const emits = defineEmits(["update:file"]);

// Functions
async function addComment(event) {
  event.preventDefault();
  const date = dayjs().format();
  const comment = {
    pageUri: page.uri + "/client-brief",
    targetPage: currentPageIndex,
    fileName: file.name,
    userUuid: user.uuid,
    text: newCommentText.value,
    date,
    id: uniqid(),
  };
  const newFile = await api.addComment(comment);
  newCommentText.value = "";
  isAddOpen.value = false;
  emits("update:file", newFile);
}

function formatDate(date) {
  const todayNumber = parseInt(dayjs().format("YYMMD"));
  const dateNumber = parseInt(dayjs(date).format("YYMMD"));

  if (dateNumber === todayNumber) {
    return "Aujourd'hui";
  }

  if (dateNumber === todayNumber - 1) {
    return "hier";
  }

  return dayjs(date).format("D MMM YY");
}

function closeAddField() {
  isAddOpen.value = false;
  newCommentText.value = "";
}

function setStatus(comment) {
  try {
    if (!user?.notifications?.comments[comment.id].isRead) {
      return "unread";
    } else {
      return undefined;
    }
  } catch (error) {
    return undefined;
  }
}

async function readNotification(notificationId) {
  const newNotifications = await api.readNotification(
    user.uuid,
    "comments",
    notificationId
  );

  user.notifications = newNotifications;
}
</script>
