<script lang="ts" setup>
import { computed, ComputedRef, Ref, ref, watch } from "vue";
import {
  fetchCourse,
  fetchModulesByCourseAndSemester,
} from "../api/fetchCourse";
import DynamicPage from "./DynamicPage.vue";
import ModuleSelection from "../components/ModuleSelection.vue";
import { Module } from "../model/module.ts";
import { useI18n } from "vue-i18n";
import moduleStore from "../store/moduleStore";
import router from "../router";

const store = moduleStore();
const { t } = useI18n({ useScope: "global" });

const courses = async () => {
  return await fetchCourse();
};

const selectedCourse: Ref<{ name: string }> = ref({ name: "" });
const countries: Ref<{ name: string }[]> = ref([]);
const semesters: ComputedRef<{ name: string; value: string }[]> = computed(
  () => [
    { name: t("courseSelection.winterSemester"), value: "ws" },
    { name: t("courseSelection.summerSemester"), value: "ss" },
  ],
);

const selectedSemester: Ref<{ name: string; value: string }> = ref(
  semesters.value[0],
);

//if semesters get changed, refresh the selected semester ref with a watcher
watch(
  semesters,
  (newValue: { name: string; value: string }[]) =>
    (selectedSemester.value =
      newValue[selectedSemester.value.value === "ws" ? 0 : 1]),
);

courses().then(
  (data) =>
    (countries.value = data.map((course) => {
      return { name: course };
    })),
);

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

async function getModules() {
  modules.value = await fetchModulesByCourseAndSemester(
    selectedCourse.value.name,
    selectedSemester.value.value,
  );
}
</script>

<template>
  <DynamicPage
    :hide-content="selectedCourse.name === ''"
    :headline="$t('courseSelection.headline')"
    :sub-title="$t('courseSelection.subTitle')"
    icon="pi pi-calendar"
    :button="{
      label: $t('courseSelection.nextStep'),
      icon: 'pi pi-arrow-right',
      disabled: store.isEmpty(),
      onClick: () => router.push('/additional-modules'),
    }"
  >
    <template #selection="{ flexSpecs }">
      <Dropdown
        v-model="selectedCourse"
        :options="countries"
        :class="flexSpecs"
        filter
        option-label="name"
        :placeholder="$t('courseSelection.courseDropDown')"
        :empty-message="$t('courseSelection.noCoursesAvailable')"
        :auto-filter-focus="true"
        @change="getModules()"
      ></Dropdown>
      <Dropdown
        v-model="selectedSemester"
        :options="semesters"
        :class="flexSpecs"
        option-label="name"
        :placeholder="$t('courseSelection.semesterDropDown')"
        @change="getModules()"
      ></Dropdown>
    </template>
    <template #content>
      <ModuleSelection
        :modules="modules"
        :selected-course="selectedCourse.name"
      />
    </template>
  </DynamicPage>
</template>
