<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">Newsletter</h1>
      </div>
    </template>
    <template #diffMain>
      <div class="flex flex-col w-full h-full gap-2 justify-center px-7">
        <Pagination
          :items="newsletters"
          :totalCount="totalCount"
          :indicateLoading="loading == 'loading'"
          @load-data="(offset, count, search) => fetchNewsletters(offset, count)"
          @search="(search) => fetchNewsletters(0, 25, true)"
        >
          <template #pageRow="{ row }: { row: NewsletterViewModel }">
            <NewsletterListItem :newsletter="row" />
          </template>
        </Pagination>

        <div class="flex flex-row gap-4">
          <button v-if="can('create', 'club', 'newsletter')" primary class="w-fit!" @click="openCreateModal">
            Newsletter 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 { useModalStore } from "@/stores/modal";
import Pagination from "@/components/Pagination.vue";
import { useAbilityStore } from "@/stores/ability";
import { useNewsletterStore } from "@/stores/admin/club/newsletter/newsletter";
import type { NewsletterViewModel } from "@/viewmodels/admin/club/newsletter/newsletter.models";
import NewsletterListItem from "@/components/admin/club/newsletter/NewsletterListItem.vue";
</script>

<script lang="ts">
export default defineComponent({
  data() {
    return {
      currentPage: 0,
      maxEntriesPerPage: 25,
    };
  },
  computed: {
    ...mapState(useNewsletterStore, ["newsletters", "totalCount", "loading"]),
    ...mapState(useAbilityStore, ["can"]),
  },
  mounted() {
    this.fetchNewsletters(0, this.maxEntriesPerPage, true);
  },
  methods: {
    ...mapActions(useNewsletterStore, ["fetchNewsletters"]),
    ...mapActions(useModalStore, ["openModal"]),
    openCreateModal() {
      this.openModal(
        markRaw(defineAsyncComponent(() => import("@/components/admin/club/newsletter/CreateNewsletterModal.vue")))
      );
    },
  },
});
</script>
