<template>
  <form ref="form" class="flex flex-col h-fit w-full border border-primary rounded-md" @submit.prevent="updateUsage">
    <div class="bg-primary p-2 text-white flex flex-row justify-between items-center">
      <p>Newsletter bei Type "{{ comType.type }}" versenden/exportieren als</p>
      <div v-if="can('create','settings','newsletter_config')" class="flex flex-row justify-end w-16">
        <button v-if="status == null" type="submit" class="!p-0 !h-fit !w-fit" title="speichern">
          <ArchiveBoxArrowDownIcon class="w-5 h-5 p-1 box-content pointer-events-none" />
        </button>
        <Spinner v-else-if="status == 'loading'" class="my-auto" />
        <SuccessCheckmark v-else-if="status?.status == 'success'" />
        <FailureXMark v-else-if="status?.status == 'failed'" />
        <button type="button" class="!p-0 !h-fit !w-fit" title="zurücksetzen" @click="resetForm">
          <ArchiveBoxXMarkIcon class="w-5 h-5 p-1 box-content pointer-events-none" />
        </button>
      </div>
    </div>
    <div class="flex flex-col p-2 gap-2">
      <div class="flex flex-row gap-2 items-center">
        <select ref="config" id="config" :value="newsletterConfig?.config ?? 'def'">
          <option value="def">Standard (pdf nur mit Name)</option>
          <option v-for="config in configs" :key="config" :value="config">{{ config == "pdf" ? "pdf mit Adresse":config }}</option>
        </select>
      </div>
    </div>
  </form>
</template>

<script setup lang="ts">
import { defineComponent, type PropType } from "vue";
import { mapState, mapActions } from "pinia";
import { ArchiveBoxArrowDownIcon, ArchiveBoxXMarkIcon } from "@heroicons/vue/24/outline";
import { useNewsletterConfigStore } from "@/stores/admin/newsletterConfig";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
import { useModalStore } from "@/stores/modal";
import { NewsletterConfigType } from "@/enums/newsletterConfigType";
import type { AxiosResponse } from "axios";
import type { CommunicationTypeViewModel } from "@/viewmodels/admin/communicationType.models";
import { useAbilityStore } from "@/stores/ability";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    comType: { type: Object as PropType<CommunicationTypeViewModel>, default: {} },
  },
  data() {
    return {
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      timeout: undefined as any,
      configs: [] as Array<string>,
    };
  },
  computed:{
    ...mapState(useNewsletterConfigStore, ["config"]),
    ...mapState(useAbilityStore, ["can"]),
    newsletterConfig() {
      return this.config.find(c => c.comTypeId == this.comType.id)
    }
  },
  mounted() {
    this.configs = Object.values(NewsletterConfigType);
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useModalStore, ["openModal"]),
    ...mapActions(useNewsletterConfigStore, ["setNewsletterConfig", "deleteNewsletterConfig"]),
    updateUsage(e: any) {
      const fromData = e.target.elements;
      const config = fromData.config.value === "def" ? null : fromData.config.value;

      this.status = "loading"
      let request: Promise<AxiosResponse<any, any>>
      if(config){
        request = this.setNewsletterConfig({
          comTypeId: this.comType.id,
          config: config
        })
      } else {
        request = this.deleteNewsletterConfig(this.comType.id)
      }
      request.then(() => {
        this.status = { status: "success" };
        this.timeout = setTimeout(() => {
          this.status = null;
        }, 2000);
      })
      .catch(() => {
        this.status = { status: "failed" };
      });
    },
    resetForm() {
      (this.$refs.config as HTMLSelectElement).value = String(this.newsletterConfig?.config ?? "def");
    },
  },
});
</script>
