<script setup lang="ts">
import { useCurrentCourseSession, useCourseData } from "@/composables";
import ItDropdownSelect from "@/components/ui/ItDropdownSelect.vue";
import { useCockpitStore } from "@/stores/cockpit";
import ItModal from "@/components/ui/ItModal.vue";
import DocumentUploadForm from "@/pages/cockpit/documentPage/DocumentUploadForm.vue";
import { computed, onMounted, ref, watch } from "vue";
import { useTranslation } from "i18next-vue";
import type { CircleDocument, DocumentUploadData } from "@/types";
import dialog from "@/utils/confirm-dialog";
import log from "loglevel";
import {
  deleteCircleDocument,
  fetchCourseSessionDocuments,
  uploadCircleDocument,
} from "@/services/files";
import { useCourseSessionsStore } from "@/stores/courseSessions";
import DocumentListItem from "@/components/circle/DocumentListItem.vue";

const cockpitStore = useCockpitStore();
const courseSession = useCurrentCourseSession();
const courseSessionsStore = useCourseSessionsStore();
const courseData = useCourseData(courseSession.value?.course.slug);

const { t } = useTranslation();

const showUploadModal = ref(false);
const showUploadErrorMessage = ref(false);
const isUploading = ref(false);

const circleDocumentsResultData = ref<CircleDocument[]>([]);
let courseSessionDocumentsUrl = "";

async function fetchDocuments() {
  const result = await fetchCourseSessionDocuments(courseSession.value?.id);
  if (result.length > 0) {
    circleDocumentsResultData.value = result;
  } else {
    circleDocumentsResultData.value = [];
  }
}

onMounted(async () => {
  log.debug("DocumentPage mounted");
  if (courseSession.value?.id) {
    courseSessionDocumentsUrl = `/api/core/document/list/${courseSession.value?.id}/`;
  }

  await fetchDocuments();
});

const dropdownLearningSequences = computed(() => {
  if (cockpitStore.currentCircle?.slug) {
    const circle = courseData.findCircle(cockpitStore.currentCircle?.slug);
    if (circle) {
      return circle.learning_sequences.map((sequence) => ({
        id: sequence.id,
        name: `${sequence.title}`,
      }));
    }
  }
  return [];
});

const circleDocuments = computed(() => {
  return circleDocumentsResultData.value.filter(
    (d) => d.learning_sequence.circle.slug === cockpitStore.currentCircle?.slug
  );
});

const deleteDocument = async (doc: CircleDocument) => {
  const options = {
    title: t("circlePage.documents.deleteModalTitle"),
    content: t("circlePage.documents.deleteModalWarning", { title: doc.name }),
  };
  try {
    await dialog.confirm(options);
    await deleteCircleDocument(doc.id, courseSessionDocumentsUrl);
    circleDocumentsResultData.value = circleDocumentsResultData.value.filter(
      (d) => d.id !== doc.id
    );
  } catch (e) {
    log.debug("rejected");
  }
};
watch(showUploadModal, () => (showUploadErrorMessage.value = false));

async function uploadDocument(data: DocumentUploadData) {
  isUploading.value = true;
  showUploadErrorMessage.value = false;
  try {
    if (!courseSessionsStore.currentCourseSession) {
      throw new Error("No course session found");
    }
    await uploadCircleDocument(
      data,
      courseSessionsStore.currentCourseSession.id,
      courseSessionDocumentsUrl
    );
    await fetchDocuments();

    showUploadModal.value = false;
    isUploading.value = false;
  } catch (error) {
    log.error(error);
    showUploadErrorMessage.value = true;
    isUploading.value = false;
  }
}
</script>

<template>
  <div class="bg-gray-200">
    <div v-if="courseSession" class="container-large">
      <nav class="py-4 pb-4">
        <router-link
          class="btn-text inline-flex items-center pl-0"
          :to="`/course/${courseSession.course.slug}/cockpit`"
        >
          <it-icon-arrow-left />
          <span>{{ t("general.back") }}</span>
        </router-link>
      </nav>
      <main>
        <div class="mb-9 flex flex-col lg:flex-row lg:items-center lg:justify-between">
          <h2>{{ t("a.Unterlagen für Teilnehmenden") }}</h2>
          <ItDropdownSelect
            :model-value="cockpitStore.currentCircle"
            class="mt-4 w-full lg:mt-0 lg:w-96"
            :items="cockpitStore.circles"
            @update:model-value="cockpitStore.setCurrentCourseCircleFromEvent"
          ></ItDropdownSelect>
        </div>

        <div class="bg-white p-6">
          <button class="btn-primary text-xl" @click="showUploadModal = true">
            {{ t("circlePage.documents.action") }}
          </button>

          <ul v-if="circleDocuments.length" class="mt-8 border-t border-t-gray-500">
            <DocumentListItem
              v-for="doc of circleDocuments"
              :key="doc.url"
              :subtitle="doc.learning_sequence.title"
              :can-delete="true"
              :doc="doc"
              @delete="deleteDocument(doc)"
            />
          </ul>
        </div>
        <ItModal v-model="showUploadModal">
          <template #title>{{ t("circlePage.documents.action") }}</template>
          <template #body>
            <DocumentUploadForm
              :learning-sequences="dropdownLearningSequences"
              :show-upload-error-message="showUploadErrorMessage"
              :is-uploading="isUploading"
              @form-submit="uploadDocument"
            />
          </template>
        </ItModal>
      </main>
    </div>
  </div>
</template>
