<script setup lang="ts">
import { useCurrentCourseSession } from "@/composables";
import ItModal from "@/components/ui/ItModal.vue";
import { computed, ref } from "vue";
import { useCSRFFetch } from "@/fetchHelpers";
import { useUserStore } from "@/stores/user";

const courseSession = useCurrentCourseSession();

const showInvitationModal = ref(false);
const inviteeEmail = ref("");

const {
  execute: refreshMentors,
  data: mentors,
  isFetching: isFetchingMentors,
} = useCSRFFetch(`/api/mentor/${courseSession.value.id}/mentors`).json();

const {
  execute: refreshInvitations,
  data: invitations,
  isFetching: isFetchingInvitations,
} = useCSRFFetch(`/api/mentor/${courseSession.value.id}/invitations`).json();

const isLoading = computed(
  () => isFetchingMentors.value || isFetchingInvitations.value
);

const hasMentors = computed(() => {
  return (
    (mentors.value && mentors.value.length > 0) ||
    (invitations.value && invitations.value.length > 0)
  );
});

const validEmail = computed(() => {
  const isSelfInvitation = Boolean(inviteeEmail.value === useUserStore().email);

  if (isSelfInvitation) {
    return false;
  }

  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(inviteeEmail.value);
});

const removeInvitation = async (invitationId: string) => {
  await useCSRFFetch(
    `/api/mentor/${courseSession.value.id}/invitations/${invitationId}/delete`
  ).delete();
  await refreshInvitations();
};

const userStore = useUserStore();

const removeMyMentor = async (mentorId: string) => {
  await useCSRFFetch(
    `/api/mentor/${courseSession.value.id}/mentors/${mentorId}/remove/${userStore.id}`
  ).delete();
  await refreshMentors();
};

const inviteMentor = async () => {
  await useCSRFFetch(`/api/mentor/${courseSession.value.id}/invitations/create`).post({
    email: inviteeEmail.value,
  });
  await refreshInvitations();
  showInvitationModal.value = false;
  inviteeEmail.value = "";
};
</script>

<template>
  <div v-if="!isLoading" class="bg-gray-200">
    <div class="flex flex-row items-center justify-between py-6">
      <h2 class="heading-2">{{ $t("a.Meine Lernbegleitung") }}</h2>
      <div>
        <button
          class="btn-secondary flex items-center"
          @click="showInvitationModal = true"
        >
          <it-icon-add class="it-icon mr-2 h-6 w-6" />
          {{ $t("a.Neue Lernbegleitung einladen") }}
        </button>
      </div>
    </div>
    <div class="bg-white px-4 py-2">
      <main>
        <div>
          <div
            v-for="invitation in invitations"
            :key="invitation.id"
            class="flex flex-col justify-between gap-4 border-b py-2 last:border-b-0 md:flex-row md:gap-16"
          >
            <div class="flex flex-col md:flex-grow md:flex-row">
              <div class="flex items-center space-x-2">
                <img
                  :alt="invitation.email"
                  class="h-11 w-11 rounded-full"
                  :src="'/static/avatars/myvbv-default-avatar.png'"
                />
                <span class="text-bold">{{ invitation.email }}</span>
              </div>
              <div class="flex items-center pl-8">
                <it-icon-info class="it-icon mr-1 h-6 w-6" />
                {{ $t("a.Die Einladung wurde noch nicht angenommen.") }}
              </div>
            </div>
            <button class="underline" @click="removeInvitation(invitation.id)">
              {{ $t("a.Entfernen") }}
            </button>
          </div>
          <div
            v-for="learningMentor in mentors"
            :key="learningMentor.id"
            class="flex flex-col justify-between gap-4 border-b py-2 last:border-b-0 md:flex-row md:gap-16"
          >
            <div class="flex items-center space-x-2">
              <img
                :alt="learningMentor.mentor.last_name"
                class="h-11 w-11 rounded-full"
                :src="learningMentor.mentor.avatar_url"
              />
              <div>
                <div class="text-bold">
                  {{ learningMentor.mentor.first_name }}
                  {{ learningMentor.mentor.last_name }}
                </div>
                {{ learningMentor.mentor.email }}
              </div>
            </div>
            <button class="underline" @click="removeMyMentor(learningMentor.id)">
              {{ $t("a.Entfernen") }}
            </button>
          </div>
        </div>
        <div v-if="!hasMentors" class="flex items-center">
          <it-icon-info class="it-icon mr-2 h-6 w-6" />
          {{ $t("a.Aktuell hast du noch keine Person als Lernbegleitung eingeladen.") }}
        </div>
      </main>
    </div>
    <ItModal v-model="showInvitationModal">
      <template #title>{{ $t("a.Neue Lernbegleitung einladen") }}</template>
      <template #body>
        <div class="flex flex-col">
          <label for="mentor-email">{{ $t("a.E-Mail Adresse") }}</label>
          <input id="mentor-email" v-model="inviteeEmail" type="email" />

          <button
            :disabled="!validEmail"
            class="btn-primary mt-8"
            @click="inviteMentor()"
          >
            {{ $t("a.Einladung abschicken") }}
          </button>
        </div>
      </template>
    </ItModal>
  </div>
</template>
