<template>
  <MainTemplate :title="`Anrede ${origin?.salutation} - Daten bearbeiten`">
    <template #headerInsert>
      <RouterLink to="../" class="text-primary">zurück zur Liste (abbrechen)</RouterLink>
    </template>
    <template #main>
      <Spinner v-if="loading == 'loading'" class="mx-auto" />
      <p v-else-if="loading == 'failed'">laden fehlgeschlagen</p>
      <form
        v-else-if="salutation != null"
        class="flex flex-col gap-4 py-2 w-full max-w-xl mx-auto"
        @submit.prevent="triggerUpdate"
      >
        <div>
          <label for="salutation">Anrede</label>
          <input type="text" id="salutation" required v-model="salutation.salutation" />
        </div>
        <div class="flex flex-row justify-end gap-2">
          <button primary-outline type="reset" class="w-fit!" :disabled="canSaveOrReset" @click="resetForm">
            verwerfen
          </button>
          <button primary type="submit" class="w-fit!" :disabled="status == 'loading' || canSaveOrReset">
            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 { useSalutationStore } from "@/stores/admin/configuration/salutation";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
import { RouterLink } from "vue-router";
import type {
  SalutationViewModel,
  UpdateSalutationViewModel,
} from "@/viewmodels/admin/configuration/salutation.models";
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 | SalutationViewModel,
      salutation: null as null | SalutationViewModel,
      timeout: null as any,
    };
  },
  computed: {
    canSaveOrReset(): boolean {
      return isEqual(this.origin, this.salutation);
    },
  },
  mounted() {
    this.fetchItem();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useSalutationStore, ["fetchSalutationById", "updateActiveSalutation"]),
    resetForm() {
      this.salutation = cloneDeep(this.origin);
    },
    fetchItem() {
      this.fetchSalutationById(parseInt(this.id ?? ""))
        .then((result) => {
          this.salutation = result.data;
          this.origin = cloneDeep(result.data);
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    triggerUpdate(e: any) {
      if (this.salutation == null) return;
      let formData = e.target.elements;
      let updateSalutation: UpdateSalutationViewModel = {
        id: this.salutation.id,
        salutation: formData.salutation.value,
      };
      this.status = "loading";
      this.updateActiveSalutation(updateSalutation)
        .then(() => {
          this.fetchItem();
          this.status = { status: "success" };
        })
        .catch((err) => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
