<script lang="ts" setup>
import { computed, ComputedRef, Ref, ref, watch } from "vue";
import {
  fetchCourse,
  fetchModulesByCourseAndSemester,
} from "../api/fetchCourse";
import ModuleSelection from "./ModuleSelection.vue";
import { Module } from "../model/module.ts";
import { useI18n } from "vue-i18n";
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>
  <div class="flex flex-column">
    <div class="flex align-items-center justify-content-center h-4rem m-2">
      <h3 class="text-4xl">
        {{ $t("courseSelection.headline") }}
        <i
          class="pi pi-calendar vertical-align-baseline"
          style="font-size: 2rem"
        ></i>
      </h3>
    </div>
    <div
      class="flex align-items-center justify-content-center h-4rem border-round m-2"
    >
      <h5 class="text-2xl">{{ $t("courseSelection.subTitle") }}</h5>
    </div>
    <div
      class="flex align-items-center justify-content-center border-round m-2"
    >
      <Dropdown
        v-model="selectedCourse"
        :options="countries"
        class="w-full md:w-25rem mx-2"
        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="w-full md:w-25rem mx-2"
        option-label="name"
        :placeholder="$t('courseSelection.semesterDropDown')"
        @change="getModules()"
      ></Dropdown>
    </div>

    <div
      class="flex align-items-center justify-content-center border-round m-2"
    >
      <div class="flex flex-wrap justify-content-center">
        <div class="flex align-items-center">
          <ModuleSelection :modules="modules" />
        </div>
      </div>
    </div>
  </div>
</template>
