<script lang="ts" setup>
import { computed, Ref, ref } from "vue";
import { Module } from "../../model/module";
import moduleStore from "../../store/moduleStore";
import { fetchAllModules } from "../../api/fetchCourse";
import { saveIndividualFeed } from "../../api/createFeed";
import tokenStore from "../../store/tokenStore";
import router from "../../router";

const tableData = computed(() =>
  moduleStore().modules.map((module: Module) => {
    return {
      Course: module.course,
      Module: module,
    };
  }),
);

const columns = ref([
  { field: "Course", header: "Course" },
  { field: "Module", header: "Module" },
]);

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, moduleStore().modules);
  await router.push("/calendar-link");
}
</script>

<template>
  <div class="flex flex-column card-container mx-8 mt-2">
    <div
      class="flex align-items-center justify-content-center border-round m-2"
    >
      <DataTable
        :value="tableData"
        edit-mode="cell"
        table-class="editable-cells-table"
        responsive-layout="scroll"
      >
        <Column
          v-for="col of columns"
          :key="col.field"
          :field="col.field"
          :header="col.header"
        >
          <template #body="{ data, field }">
            <div>
              {{
                field === "Module" ? data[field].userDefinedName : data[field]
              }}
            </div>
          </template>
          <template #editor="{ data, field }">
            <template v-if="field !== 'Module'">
              <div>{{ data[field] }}</div>
            </template>
            <template v-else>
              <InputText
                v-model="data[field].userDefinedName"
                class="w-full"
                autofocus
              />
            </template>
          </template>
        </Column>
        <Column>
          <template #body="{ data }">
            <Button
              icon="pi pi-trash"
              severity="danger"
              outlined
              rounded
              aria-label="Cancel"
              @click="deleteModule(data['Module'])"
            />
          </template>
        </Column>
      </DataTable>
    </div>
    <div
      class="flex align-items-center justify-content-center border-round m-2"
    >
      <Button label="Save Calendar" @click="finalStep()" />
    </div>
  </div>
</template>

<style scoped></style>
