<template>
  <MainTemplate>
    <template #topBar>
      <div class="flex flex-row items-center justify-between pt-5 pb-3 px-7">
        <h1 class="font-bold text-xl h-8">Mitglieder</h1>
      </div>
    </template>
    <template #diffMain>
      <div class="flex flex-col w-full h-full gap-2 justify-center px-7">
        <Pagination
          :items="members"
          :totalCount="totalCount"
          :indicateLoading="loading == 'loading'"
          @load-data="(offset, count, search) => fetchMembers(offset, count)"
          @search="(search) => fetchMembers(0, 25, true)"
        >
          <template #pageRow="{ row }: { row: MemberViewModel }">
            <MemberListItem :member="row" />
          </template>
        </Pagination>

        <div class="flex flex-row gap-4">
          <button primary class="!w-fit" @click="openCreateModal">Mitglied erstellen</button>
        </div>
      </div>
    </template>
  </MainTemplate>
</template>

<script setup lang="ts">
import { defineAsyncComponent, defineComponent, markRaw } from "vue";
import { mapActions, mapState } from "pinia";
import MainTemplate from "@/templates/Main.vue";
import { ChevronRightIcon, ChevronLeftIcon } from "@heroicons/vue/20/solid";
import { useMemberStore } from "@/stores/admin/member";
import MemberListItem from "@/components/admin/club/member/MemberListItem.vue";
import { useModalStore } from "@/stores/modal";
import Pagination from "../../../components/Pagination.vue";
import type { MemberViewModel } from "../../../viewmodels/admin/member.models";
</script>

<script lang="ts">
export default defineComponent({
  data() {
    return {
      currentPage: 0,
      maxEntriesPerPage: 25,
    };
  },
  computed: {
    ...mapState(useMemberStore, ["members", "totalCount", "loading"]),
    entryCount() {
      return this.totalCount ?? this.members.length;
    },
    showingStart() {
      return this.currentPage * this.maxEntriesPerPage;
    },
    showingEnd() {
      let max = this.currentPage * this.maxEntriesPerPage + this.maxEntriesPerPage;
      if (max > this.entryCount) max = this.entryCount;
      return max;
    },
    showingText() {
      return `${this.entryCount != 0 ? this.showingStart + 1 : 0} - ${this.showingEnd}`;
    },
    countOfPages() {
      return Math.ceil(this.entryCount / this.maxEntriesPerPage);
    },
    displayedPagesNumbers(): Array<number | "."> {
      //indicate if "." or page number gets pushed
      let stateOfPush = false;

      return [...new Array(this.countOfPages)].reduce((acc, curr, index) => {
        if (
          // always display first 2 pages
          index <= 1 ||
          // always display last 2 pages
          index >= this.countOfPages - 2 ||
          // always display 1 pages around current page
          (this.currentPage - 1 <= index && index <= this.currentPage + 1)
        ) {
          acc.push(index);
          stateOfPush = false;
          return acc;
        }
        // abort if placeholder already added to array
        if (stateOfPush == true) return acc;
        // show placeholder if pagenumber is not actively rendered
        acc.push(".");
        stateOfPush = true;

        return acc;
      }, []);
    },
    visibleRows() {
      return this.filterData(this.members, this.showingStart, this.showingEnd);
    },
  },
  mounted() {
    this.fetchMembers(0, this.maxEntriesPerPage, true);
  },
  methods: {
    ...mapActions(useMemberStore, ["fetchMembers"]),
    ...mapActions(useModalStore, ["openModal"]),
    loadPage(newPage: number | ".") {
      if (newPage == ".") return;
      if (newPage < 0 || newPage >= this.countOfPages) return;

      let pageStart = newPage * this.maxEntriesPerPage;
      let pageEnd = newPage * this.maxEntriesPerPage + this.maxEntriesPerPage;
      if (pageEnd > this.entryCount) pageEnd = this.entryCount;

      let loadedElementCount = this.filterData(this.members, pageStart, pageEnd).length;
      if (loadedElementCount < this.maxEntriesPerPage) this.fetchMembers(pageStart, this.maxEntriesPerPage);

      this.currentPage = newPage;
    },
    filterData(array: Array<any>, start: number, end: number): Array<any> {
      return array.filter((elem, index) => (elem?.tab_pos ?? index) >= start && (elem?.tab_pos ?? index) < end);
    },
    openCreateModal() {
      this.openModal(
        markRaw(defineAsyncComponent(() => import("@/components/admin/club/member/CreateMemberModal.vue")))
      );
    },
  },
});
</script>
