<script lang="ts" setup>
import { defineAsyncComponent, inject, ref, Ref} from "vue";
import { Module } from "../model/module.ts";
import { fetchAllModules } from "../api/fetchCourse.ts";
import moduleStore from "../store/moduleStore.ts";
import { FilterMatchMode } from "primevue/api";
import { DataTableRowSelectEvent, DataTableRowUnselectEvent } from "primevue/datatable";
import { useDialog } from "primevue/usedialog";
import router from "../router";
import { fetchModule } from "../api/fetchModule.ts";
import { useI18n } from "vue-i18n";

const dialog = useDialog();
const { t } = useI18n({ useScope: "global" });

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

const store = moduleStore();
if (store.isEmpty()) {
  router.replace("/");
}

const mobilePage = inject("mobilePage") as Ref<boolean>;
const modules: Ref<Module[]> = ref([]);
const filters = ref({
  course: {
    value: null,
    matchMode: FilterMatchMode.CONTAINS,
  },
  name: {
    value: null,
    matchMode: FilterMatchMode.CONTAINS,
  },
  prof: {
    value: null,
    matchMode: FilterMatchMode.CONTAINS,
  },
});

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

async function nextStep() {
  await router.push("/rename-modules");
}

const ModuleInformation = defineAsyncComponent(
  () => import("../components/ModuleInformation.vue"),
);

async function showInfo(module: Module) {
  await fetchModule(module).then((data) => {
    module = data;
  });
  dialog.open(ModuleInformation, {
    class: "w-full m-0",
    props: {
        style: {
          width: "80vw",
        },
        breakpoints: {
          "992px": "100vw",
          "640px": "100vw",
        },
        modal: true,
      },
    data: {
      module: module,
    },
  });
}

function selectModule(event: DataTableRowSelectEvent) {
  store.addModule(event.data);
}

function unselectModule(event: DataTableRowUnselectEvent) {
  store.removeModule(event.data);
}

</script>

<template>
  <div class="flex flex-column align-items-center w-full mb-7">
    <div class="flex align-items-center justify-content-center m-2">
      <h3>
        {{ $t("additionalModules.subTitle") }}
      </h3>
    </div>
    <div class="m-2 lg:w-10 w-full">
      <DynamicDialog />
      <DataTable
        id="dt-responsive-table"
        v-model:filters="filters"
        :selection="store.getAllModules()"
        :value="modules"
        data-key="uuid"
        paginator
        :rows="10"
        :rows-per-page-options="[5, 10, 20, 50]"
        paginator-template="FirstPageLink PrevPageLink CurrentPageReport NextPageLink LastPageLink RowsPerPageDropdown"
        :current-page-report-template="
          $t('additionalModules.paginator.from') +
          '{first}' + 
          $t('additionalModules.paginator.to') + 
          '{last}' + 
          $t('additionalModules.paginator.of') + 
          '{totalRecords}'
        "
        filter-display="row"
        :loading="!modules.length"
        loading-icon="pi pi-spinner"
        :show-gridlines="true"
        :striped-rows="true"
        :select-all="false"
        :size="mobilePage ? 'small' : 'large'"
        @row-select="selectModule"
        @row-unselect="unselectModule"
      >
        <Column selection-mode="multiple">
        </Column>

        <Column
          field="course"
          :header="$t('additionalModules.course')"
          :show-clear-button="false"
          :show-filter-menu="false"
        >
          <template #filter="{ filterModel, filterCallback }">
            <InputText
              v-model="filterModel.value"
              type="text"
              class="p-column-filter max-w-10rem"
              @input="filterCallback()"
            />
          </template>
        </Column>
        <Column
          field="name"
          :header="$t('additionalModules.module')"
          :show-clear-button="false"
          :show-filter-menu="false"
        >
          <template #filter="{ filterModel, filterCallback }">
            <InputText
              v-model="filterModel.value"
              type="text"
              class="p-column-filter"
              @input="filterCallback()"
            />
          </template>
        </Column>
        <Column
          field="prof"
          :header="$t('additionalModules.professor')"
          :show-clear-button="false"
          :show-filter-menu="false"
        >
        </Column>
        <Column 
          :header="$t('additionalModules.info')"
        >
          <template #body="slotProps">
            <Button
              icon="pi pi-info"
              severity="secondary"
              rounded
              outlined
              :aria-label="$t('additionalModules.info-long')"
              class="small-button"
              @click.stop="showInfo(slotProps.data)"
            ></Button>
          </template>
        </Column>
        <template #footer>
          <div class="py-2 px-3">
            {{ 
              t('additionalModules.footerModulesSelected', { count: store?.countModules() ?? 0 })
            }} 
          </div>
        </template>
      </DataTable>
    </div>
    <div class="flex align-items-center justify-content-end h-4rem m-2 w-full lg:w-10">
      <Button 
        :disabled="store.isEmpty()"
        @click="nextStep()"
        class="col-12 md:col-4 mb-3 align-self-end"
        icon="pi pi-arrow-right"
        :label="$t('additionalModules.nextStep')"
      />
    </div>
  </div>
</template>

<style scoped>
:deep(.custom-multiselect) {
  width: 50rem;
}

:deep(.custom-multiselect li) {
  height: unset;
}

.small-button.p-button {
  width: 2rem;
  height: 2rem;
  padding: 0;
}

:deep(.p-filter-column .p-checkbox .p-component) {
  display: none !important;
}
</style>
