<template>
  <div class="flex flex-col gap-2 h-full w-full overflow-y-auto">
    <Spinner v-if="loading == 'loading'" class="mx-auto" />
    <p v-else-if="loading == 'failed'" @click="fetchNewsletterRecipients" class="cursor-pointer">
      &#8634; laden fehlgeschlagen
    </p>

    <select v-model="recipientsByQueryId">
      <option value="def">Optional</option>
      <option v-for="query in queries" :key="query.id" :value="query.id">{{ query.title }}</option>
    </select>
    <p>Empfänger durch gespeicherte Abfrage</p>
    <div class="flex flex-col gap-2 grow overflow-y-auto">
      <div
        v-for="member in queried"
        :key="member.id"
        class="flex flex-row h-fit w-full border border-primary rounded-md bg-primary p-2 text-white justify-between items-center"
      >
        <div>
          <p>{{ member.lastname }}, {{ member.firstname }} {{ member.nameaffix ? `- ${member.nameaffix}` : "" }}</p>
          <p>Newsletter senden an Typ: {{ member.sendNewsletter?.type.type }}</p>
        </div>
      </div>
    </div>

    <MemberSearchSelect
      title="weitere Empfänger suchen"
      v-model="recipients"
      :disabled="!can('create', 'club', 'newsletter')"
    />

    <p>Ausgewählte Empfänger</p>
    <div class="flex flex-col gap-2 grow overflow-y-auto">
      <div
        v-for="member in selected"
        :key="member.id"
        class="flex flex-row h-fit w-full border border-primary rounded-md bg-primary p-2 text-white justify-between items-center"
      >
        <div>
          <p>{{ member.lastname }}, {{ member.firstname }} {{ member.nameaffix ? `- ${member.nameaffix}` : "" }}</p>
          <p>Newsletter senden an Typ: {{ member.sendNewsletter?.type.type }}</p>
        </div>

        <TrashIcon
          v-if="can('create', 'club', 'newsletter')"
          class="w-5 h-5 p-1 box-content cursor-pointer"
          @click="removeSelected(member.id)"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapActions, mapState, mapWritableState } from "pinia";
import Spinner from "@/components/Spinner.vue";
import {
  Combobox,
  ComboboxLabel,
  ComboboxInput,
  ComboboxButton,
  ComboboxOptions,
  ComboboxOption,
  TransitionRoot,
} from "@headlessui/vue";
import { CheckIcon, ChevronUpDownIcon } from "@heroicons/vue/20/solid";
import { TrashIcon } from "@heroicons/vue/24/outline";
import { useMemberStore } from "@/stores/admin/club/member/member";
import type { MemberViewModel } from "@/viewmodels/admin/club/member/member.models";
import { useNewsletterStore } from "@/stores/admin/club/newsletter/newsletter";
import { useNewsletterRecipientsStore } from "@/stores/admin/club/newsletter/newsletterRecipients";
import { useAbilityStore } from "@/stores/ability";
import { useQueryStoreStore } from "@/stores/admin/settings/queryStore";
import { useQueryBuilderStore } from "@/stores/admin/club/queryBuilder";
import cloneDeep from "lodash.clonedeep";
import MemberSearchSelect from "@/components/admin/MemberSearchSelect.vue";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    newsletterId: String,
  },
  watch: {
    recipientsByQuery() {
      this.loadQuery();
    },
  },
  data() {
    return {
      query: "" as String,
      members: [] as Array<MemberViewModel>,
    };
  },
  computed: {
    ...mapWritableState(useNewsletterRecipientsStore, ["recipients", "loading"]),
    ...mapWritableState(useNewsletterStore, ["activeNewsletterObj"]),
    ...mapState(useQueryStoreStore, ["queries"]),
    ...mapState(useQueryBuilderStore, ["data"]),
    ...mapState(useAbilityStore, ["can"]),
    selected(): Array<MemberViewModel> {
      return this.members
        .filter((m) => this.recipients.includes(m.id))
        .sort((a, b) => {
          if (a.lastname < b.lastname) return -1;
          if (a.lastname > b.lastname) return 1;
          if (a.firstname < b.firstname) return -1;
          if (a.firstname > b.firstname) return 1;
          return 0;
        });
    },
    queried(): Array<MemberViewModel> {
      if (this.recipientsByQueryId == "def") return [];
      let keys = Object.keys(this.data?.[0] ?? {});
      let memberKey = keys.find((k) => k.includes("member_id"));
      return this.members.filter((m) =>
        this.data
          .map((t) => ({
            id: t.id,
            ...(memberKey ? { memberId: t[memberKey] } : {}),
          }))
          .some((d) => (d.memberId ?? d.id) == m.id)
      );
    },
    recipientsByQueryId: {
      get() {
        return this.activeNewsletterObj?.recipientsByQueryId ?? "def";
      },
      set(val: string) {
        if (this.activeNewsletterObj == undefined) return;
        if (val == "def") {
          this.activeNewsletterObj.recipientsByQueryId = null;
          this.activeNewsletterObj.recipientsByQuery = null;
        } else if (this.queries.find((q) => q.id == parseInt(val))) {
          this.activeNewsletterObj.recipientsByQueryId = parseInt(val);
          this.activeNewsletterObj.recipientsByQuery = cloneDeep(this.queries.find((q) => q.id == parseInt(val)));
          this.sendQuery(0, 1000, this.recipientsByQuery?.query);
        }
      },
    },
    recipientsByQuery() {
      return this.activeNewsletterObj?.recipientsByQuery;
    },
  },
  mounted() {
    // this.fetchNewsletterRecipients();
    this.fetchQueries();
    this.loadQuery();
    this.loadMembers();
  },
  methods: {
    ...mapActions(useMemberStore, ["getAllMembers"]),
    ...mapActions(useNewsletterRecipientsStore, ["fetchNewsletterRecipients"]),
    ...mapActions(useQueryStoreStore, ["fetchQueries"]),
    ...mapActions(useQueryBuilderStore, ["sendQuery"]),
    removeSelected(id: number) {
      let index = this.recipients.findIndex((s) => s == id);
      if (index != -1) {
        this.recipients.splice(index, 1);
      }
    },
    loadMembers() {
      this.getAllMembers()
        .then((res) => {
          this.members = res.data;
        })
        .catch(() => {});
    },
    loadQuery() {
      if (this.recipientsByQuery) {
        this.sendQuery(0, 1000, this.recipientsByQuery.query);
      }
    },
  },
});
</script>
