<template>
  <MainTemplate>
    <template #headerInsert>
      <RouterLink to="../" class="text-primary">zurück zur Liste (abbrechen)</RouterLink>
    </template>
    <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">Template {{ origin?.template }} - Daten bearbeiten</h1>
      </div>
    </template>
    <template #main>
      <Spinner v-if="loading == 'loading'" class="mx-auto" />
      <p v-else-if="loading == 'failed'">laden fehlgeschlagen</p>
      <form
        v-else-if="template != null"
        class="flex flex-col gap-4 py-2 w-full h-full mx-auto"
        @submit.prevent="triggerUpdate"
      >
        <div class="flex flex-col xl:flex-row gap-4">
          <div class="w-full">
            <label for="template">Bezeichnung</label>
            <input type="text" id="template" required v-model="template.template" />
          </div>
          <div class="w-full">
            <label for="description">Beschreibung (optional)</label>
            <input type="text" id="description" v-model="template.description" />
          </div>
        </div>
        <div class="flex flex-col w-full grow max-xl:hidden">
          <EmailEditor
            ref="emailEditor"
            minHeight="100%"
            :options="options"
            @ready="editorReady"
            @load="loadDesign()"
          />
        </div>
        <div class="px-7 xl:hidden">
          <p>
            Der externe Editor ist nicht auf kleine Auflösungen optimiert. Wechseln Sie auf ein Desktop-Gerät, einen
            größeren Bildschirm oder ändern Sie die Skalierung dieser Seite.
          </p>
        </div>
        <div class="flex flex-row justify-end gap-2">
          <button primary-outline type="reset" class="!w-fit" :disabled="status == 'loading'" @click="resetForm">
            verwerfen
          </button>
          <button primary type="submit" class="!w-fit" :disabled="status == 'loading'">speichern</button>
          <Spinner v-if="status == 'loading'" class="my-auto" />
          <SuccessCheckmark v-else-if="status?.status == 'success'" />
          <FailureXMark v-else-if="status?.status == 'failed'" />
        </div>
      </form>
    </template>
  </MainTemplate>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapState, mapActions } from "pinia";
import MainTemplate from "@/templates/Main.vue";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
import { RouterLink } from "vue-router";
import { EmailEditor } from "vue-email-editor";
import { configureEditor, exportEditor, loadEditor, options } from "@/helpers/unlayerEditor";
import type { TemplateViewModel, UpdateTemplateViewModel } from "../../../../viewmodels/admin/template.models";
import { useTemplateStore } from "../../../../stores/admin/template";
import cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    id: String,
  },
  data() {
    return {
      loading: "loading" as "loading" | "fetched" | "failed",
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      origin: null as null | TemplateViewModel,
      template: null as null | TemplateViewModel,
      timeout: null as any,
    };
  },
  computed: {
    canSaveOrReset(): boolean {
      return isEqual(this.origin, this.template);
    },
  },
  mounted() {
    this.fetchItem();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useTemplateStore, ["fetchTemplateById", "updateActiveTemplate"]),
    editorReady() {
      configureEditor(this.$refs.emailEditor as typeof EmailEditor);
    },
    loadBlank() {
      loadEditor(this.$refs.emailEditor as typeof EmailEditor);
    },
    loadDesign() {
      loadEditor(this.$refs.emailEditor as typeof EmailEditor, this.origin?.design);
    },
    resetForm() {
      this.template = cloneDeep(this.origin);
      this.loadDesign();
    },
    fetchItem() {
      this.fetchTemplateById(parseInt(this.id ?? ""))
        .then((result) => {
          this.template = result.data;
          this.origin = cloneDeep(result.data);
          this.loading = "fetched";
        })
        .catch((err) => {
          console.log(err);
          this.loading = "failed";
        });
    },
    triggerUpdate(e: any) {
      if (this.template == null) return;
      let { design, headerHTML, bodyHTML, footerHTML } = exportEditor(this.$refs.emailEditor as typeof EmailEditor);
      let formData = e.target.elements;
      let updateTemplate: UpdateTemplateViewModel = {
        id: this.template.id,
        template: formData.template.value,
        description: formData.description.value,
        design,
        headerHTML,
        bodyHTML,
        footerHTML,
      };
      this.status = "loading";
      this.updateActiveTemplate(updateTemplate)
        .then(() => {
          this.fetchItem();
          this.status = { status: "success" };
        })
        .catch((err) => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
