<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-show="loading == 'fetched' && template != null"
        class="flex flex-col gap-4 py-2 w-full h-full mx-auto"
        @submit.prevent="triggerUpdate"
      >
        <div v-if="template != null" 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 v-if="contextLoading == 'loading'" class="flex flex-col gap-2 items-center">
          <p>Lade Template-Anzeige</p>
          <Spinner />
        </div>
        <div ref="grapesEditor" id="grapesEditor"></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 { configureEditor } from "@/helpers/grapesEditor";
import type { TemplateViewModel, UpdateTemplateViewModel } from "@/viewmodels/admin/settings/template.models";
import { useTemplateStore } from "@/stores/admin/settings/template";
import cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";
import grapesjs, { Editor } from "grapesjs";
import grapesNewsletter from "grapesjs-preset-newsletter";
import "grapesjs/dist/css/grapes.min.css";
</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,
      editor: null as null | Editor,
      contextLoading: "loading" as "loading" | "loaded" | "failed",
    };
  },
  computed: {
    canSaveOrReset(): boolean {
      return isEqual(this.origin, this.template);
    },
  },
  mounted() {
    this.fetchItem();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
    localStorage.removeItem("gjsProject");
  },
  methods: {
    ...mapActions(useTemplateStore, ["fetchTemplateById", "updateActiveTemplate"]),
    initEditor() {
      this.editor = grapesjs.init({
        container: "#grapesEditor",
        height: "100%",
        width: "100%",
        fromElement: true,
        telemetry: false,
        showDevices: false,
        deviceManager: {
          devices: [
            {
              id: "tablet",
              name: "Tablet",
              width: "768px",
              widthMedia: "992px",
            },
          ],
        },
        plugins: [grapesNewsletter],
      });
      configureEditor(this.editor);
    },
    loadDesign() {
      this.contextLoading = "loading";
      this.editor?.destroy();
      localStorage.setItem("gjsProject", JSON.stringify(this.origin?.design ?? {}));
      setTimeout(() => {
        this.initEditor();
        this.contextLoading = "loaded";
      }, 1000);
    },
    resetForm() {
      this.template = cloneDeep(this.origin);
      this.loadDesign();
    },
    fetchItem(fromSave: boolean = false) {
      this.fetchTemplateById(parseInt(this.id ?? ""))
        .then((result) => {
          this.template = result.data;
          this.origin = cloneDeep(result.data);
          this.loading = "fetched";
          if (!fromSave) this.loadDesign();
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    triggerUpdate(e: any) {
      if (this.template == null) return;
      let formData = e.target.elements;
      const htmlContent = this.editor?.getHtml();
      const cssContent = this.editor?.getCss();
      const html = `<style>${cssContent}</style>${htmlContent}`;

      let updateTemplate: UpdateTemplateViewModel = {
        id: this.template.id,
        template: formData.template.value,
        description: formData.description.value,
        design: this.editor?.getProjectData() ?? {},
        html,
      };
      this.status = "loading";
      this.updateActiveTemplate(updateTemplate)
        .then(() => {
          this.fetchItem(true);
          this.status = { status: "success" };
        })
        .catch((err) => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
