<template>
  <div class="w-full md:max-w-md">
    <div class="flex flex-col items-center">
      <p class="text-xl font-medium">Newsletter Druck Empfänger</p>
    </div>
    <br />

    <p v-if="receivers.length == 0">keine Empfänger gefunden</p>
    <p v-else>{{ receivers.length }} Empfänger gefunden</p>
    <div class="flex flex-col gap-2 h-96 overflow-y-scroll">
      <p
        v-for="rec in receivers"
        :key="rec.id"
        class="bg-primary p-2 text-white flex flex-row justify-between items-center rounded-md"
      >
        {{ rec.lastname }}, {{ rec.firstname }}
      </p>
    </div>

    <div class="flex flex-row gap-4 py-2 w-full">
      <button primary @click="start">Druck starten</button>
      <button primary-outline @click="closeModal">Druck abbrechen</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, defineComponent, markRaw } from "vue";
import { mapState, mapActions } from "pinia";
import { useModalStore } from "@/stores/modal";
import { useNewsletterPrintoutStore } from "@/stores/admin/club/newsletter/newsletterPrintout";
import type { MemberViewModel } from "@/viewmodels/admin/club/member/member.models";
</script>

<script lang="ts">
export default defineComponent({
  data() {
    return {
      receivers: [] as Array<MemberViewModel>,
      error: null as null | string,
    };
  },
  mounted() {
    this.fetchNewsletterPrintReceivers()
      .then((res) => {
        this.receivers = res.data;
      })
      .catch((err) => {
        this.error = "Fehler beim Laden der Empfänger";
      });
  },
  methods: {
    ...mapActions(useNewsletterPrintoutStore, ["fetchNewsletterPrintReceivers", "createNewsletterPrintout"]),
    ...mapActions(useModalStore, ["openModal", "closeModal"]),
    start() {
      this.createNewsletterPrintout();
      this.openPdfLogs();
    },
    openPdfLogs() {
      this.openModal(
        markRaw(
          defineAsyncComponent(() => import("@/components/admin/club/newsletter/NewsletterPrintingProgressModal.vue"))
        )
      );
    },
  },
});
</script>
