<script lang="ts" setup>
import { computed, ComputedRef, Ref, ref, watch } from "vue";
import {
  fetchCourse,
  fetchModulesByCourseAndSemester,
} from "../api/fetchCourse";
import ModuleSelection from "../components/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 align-items-center transition-all transition-duration-500 transition-ease-in-out mt-0"
    :class="{'md:mt-8': modules.length === 0}"
  >
    <div class="flex align-items-center justify-content-center gap-2 mx-2">
      <h3 class="text-4xl">
        {{ $t("courseSelection.headline") }}
      </h3>
      <i
        class="pi pi-calendar"
        style="font-size: 2rem"
      ></i>
    </div>
    <div
      class="flex justify-content-center"
    >
      <h5 class="text-2xl m-2">{{ $t("courseSelection.subTitle") }}</h5>
    </div>
    <div
      class="flex flex-wrap mx-0 gap-2 my-4 w-full lg:w-8"
    >
      <Dropdown
        v-model="selectedCourse"
        :options="countries"
        class="flex-1 m-0"
        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="flex-1 m-0"
        option-label="name"
        :placeholder="$t('courseSelection.semesterDropDown')"
        @change="getModules()"
      ></Dropdown>
    </div>
    <ModuleSelection
      :modules="modules"
      class="lg:w-8"
    />
  </div>
</template>
