<script lang="ts" setup>
import { computed, inject, Ref, ref } from "vue";
import { Module } from "@/model/module.ts";
import moduleStore from "../../store/moduleStore";
import { fetchAllModules } from "@/api/fetchCourse.ts";
import { deleteIndividualFeed, saveIndividualFeed } from "@/api/createFeed.ts";
import tokenStore from "../../store/tokenStore";
import router from "@/router";
import ModuleTemplateDialog from "../../components/ModuleTemplateDialog.vue";
import { onlyWhitespace } from "@/helpers/strings.ts";
import { useI18n } from "vue-i18n";
import { useToast } from "primevue/usetoast";
const { t } = useI18n({ useScope: "global" });

const toast = useToast();
const visible = ref(false);

defineProps({
  class: {
    type: String,
    default: "",
  },
});

const store = moduleStore();

const tableData = computed(() =>
  store.getAllModules().map((module: Module) => {
    return {
      Course: module.course,
      Module: module,
    };
  }),
);
const mobilePage = inject("mobilePage") as Ref<boolean>;

const columns = computed(() => [
  { field: "Course", header: t("moduleInformation.course") },
  { field: "Module", header: t("moduleInformation.module") },
  { field: "Reminder", header: t("renameModules.reminder") },
]);

const fetchedModules = async () => {
  return await fetchAllModules();
};

function deleteModule(module: Module) {
  console.debug(module);
  moduleStore().removeModule(module);
}

const modules: Ref<Module[]> = ref([]);

fetchedModules().then(
  (data) =>
    (modules.value = data.map((module: Module) => {
      return module;
    })),
);

async function finalStep() {
  await saveIndividualFeed(tokenStore().token, store.getAllModules());
  await router.push("/calendar-link");
}

async function deleteFeed() {
  deleteIndividualFeed(tokenStore().token).then(
    () => {
      toast.add({
        severity: "success",
        summary: t("editCalendarView.toast.success"),
        detail: t("editCalendarView.toast.successDetail"),
        life: 3000,
      });
      visible.value = false;
      router.push("/");
    },
    () => {
      toast.add({
        severity: "error",
        summary: t("editCalendarView.toast.error"),
        detail: t("editCalendarView.toast.errorDetail"),
        life: 3000,
      });
    },
  );
}
</script>

<template>
  <div class="flex flex-column align-items-center mb-7">
    <div class="flex align-items-center justify-content-center m-2 gap-2">
      <h3>{{ $t("renameModules.subTitle") }}</h3>
      <ModuleTemplateDialog />
    </div>
    <div class="w-full lg:w-8 flex flex-column">
      <div class="card flex align-items-center justify-content-center my-2">
        <DataTable
          :value="tableData"
          edit-mode="cell"
          table-class="editable-cells-table"
          responsive-layout="scroll"
          :size="mobilePage ? 'small' : 'large'"
          class="w-full"
        >
          <template #header>
            <div class="flex align-items-center justify-content-end">
              {{ $t("renameModules.enableAllNotifications") }}
              <InputSwitch
                class="mx-4"
                :model-value="
                  tableData.reduce(
                    (acc, curr) => acc && curr.Module.reminder,
                    true,
                  )
                "
                @update:model-value="
                  tableData.forEach(
                    (module) => (module.Module.reminder = $event),
                  )
                "
              />
            </div>
          </template>
          <Column
            v-for="col of columns"
            :key="col.field"
            :field="col.field"
            :header="col.header"
            :class="col.field === 'Reminder' ? 'text-center' : ''"
          >
            <!-- Text Body -->
            <template #body="{ data, field }">
              <template v-if="field === 'Module'">
                {{
                  onlyWhitespace(data[field].userDefinedName)
                    ? data[field].name
                    : data[field].userDefinedName
                }}
              </template>
              <template v-else-if="field === 'Reminder'">
                <div class="flex align-items-start">
                  <Button
                    icon="pi pi-bell"
                    :severity="data.Module.reminder ? 'warning' : 'secondary'"
                    rounded
                    outlined
                    class="small-button"
                    @click="data.Module.reminder = !data.Module.reminder"
                  />
                </div>
              </template>
              <template v-else>
                {{ data[field] }}
              </template>
            </template>
            <!-- Editor Body -->
            <template #editor="{ data, field }">
              <template v-if="field === 'Module'">
                <InputText
                  v-model="data[field].userDefinedName"
                  class="w-full"
                  autofocus
                />
              </template>
              <template v-else-if="field === 'Reminder'">
                <div class="flex align-items-start">
                  <Button
                    icon="pi pi-bell"
                    :severity="data.Module.reminder ? 'warning' : 'secondary'"
                    rounded
                    outlined
                    class="small-button"
                    @click="data.Module.reminder = !data.Module.reminder"
                  />
                </div>
              </template>
              <template v-else>
                {{ data[field] }}
              </template>
            </template>
          </Column>
          <Column field="module">
            <template #body="{ data }">
              <Button
                icon="pi pi-trash"
                class="small-button"
                severity="danger"
                outlined
                rounded
                aria-label="Cancel"
                @click="deleteModule(data['Module'])"
              />
            </template>
          </Column>
          <template #footer>
            <div
              class="flex flex-column sm:flex-row flex-wrap justify-content-between gap-2 w-full"
            >
              <Button
                type="button"
                severity="danger"
                outlined
                icon="pi pi-trash"
                :label="$t('editCalendarView.delete')"
                @click="visible = true"
              />
              <Button
                type="button"
                severity="info"
                outlined
                icon="pi pi-plus"
                :label="$t('editCalendarView.addModules')"
                @click="router.push('edit-additional-modules')"
              />
              <Button
                type="button"
                severity="success"
                outlined
                icon="pi pi-save"
                :label="$t('editCalendarView.save')"
                @click="finalStep()"
              />
            </div>
          </template>
        </DataTable>
      </div>
    </div>
  </div>
  <div class="card flex justify-content-center">
    <Dialog
      v-model:visible="visible"
      modal
      header="Header"
      :style="{ width: '50rem' }"
      :breakpoints="{ '1199px': '75vw', '575px': '90vw' }"
    >
      <template #header>
        <div
          class="inline-flex align-items-center justify-content-center gap-2"
        >
          <span class="font-bold white-space-nowrap">{{
            $t("editCalendarView.dialog.headline")
          }}</span>
        </div>
      </template>
      <p class="m-0">{{ $t("editCalendarView.dialog.subTitle") }}</p>
      <template #footer>
        <Button
          :label="$t('editCalendarView.dialog.delete')"
          severity="danger"
          icon="pi pi-trash"
          autofocus
          @click="deleteFeed()"
        />
      </template>
    </Dialog>
  </div>
</template>

<style scoped></style>
