<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">Kommunikationsart {{ origin?.type }} - 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="communicationType != null"
        class="flex flex-col gap-4 py-2 w-full max-w-xl mx-auto"
        @submit.prevent="triggerUpdate"
      >
        <div>
          <label for="communicationType">Bezeichnung</label>
          <input type="text" id="communicationType" required v-model="communicationType.type" />
        </div>
        <div>
          <Listbox v-model="communicationType.fields" multiple>
            <ListboxLabel>Felder</ListboxLabel>
            <div class="relative mt-1">
              <ListboxButton
                class="rounded-md shadow-sm relative block w-full px-3 py-2 border border-gray-300 focus:border-primary placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-0 focus:z-10 sm:text-sm resize-none"
              >
                <span class="block truncate w-full text-start"> {{ communicationType.fields.join(", ") }}</span>
                <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                  <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                </span>
              </ListboxButton>

              <transition
                leave-active-class="transition duration-100 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
              >
                <ListboxOptions
                  class="absolute mt-1 max-h-60 z-20 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black/5 focus:outline-none sm:text-sm h-32 overflow-y-auto"
                >
                  <ListboxOption
                    v-slot="{ active, selected }"
                    v-for="field in availableFields"
                    :key="field"
                    :value="field"
                    as="template"
                  >
                    <li
                      :class="[
                        active ? 'bg-red-200 text-amber-900' : 'text-gray-900',
                        'relative cursor-default select-none py-2 pl-10 pr-4',
                      ]"
                    >
                      <span :class="[selected ? 'font-medium' : 'font-normal', 'block truncate']">{{ field }}</span>
                      <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-primary">
                        <CheckIcon class="h-5 w-5" aria-hidden="true" />
                      </span>
                    </li>
                  </ListboxOption>
                </ListboxOptions>
              </transition>
            </div>
          </Listbox>
        </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 { useCommunicationTypeStore } from "@/stores/admin/communicationType";
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 {
  CommunicationTypeViewModel,
  UpdateCommunicationTypeViewModel,
} from "@/viewmodels/admin/communicationType.models";
import { Listbox, ListboxButton, ListboxOptions, ListboxOption, ListboxLabel } from "@headlessui/vue";
import { CheckIcon, ChevronUpDownIcon } from "@heroicons/vue/20/solid";
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 | CommunicationTypeViewModel,
      communicationType: null as null | CommunicationTypeViewModel,
      timeout: null as any,
    };
  },
  computed: {
    ...mapState(useCommunicationTypeStore, ["availableFields"]),
    canSaveOrReset(): boolean {
      return isEqual(this.origin, this.communicationType);
    },
  },
  mounted() {
    this.fetchItem();
    this.fetchAvailableFields();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useCommunicationTypeStore, [
      "fetchCommunicationTypeById",
      "updateActiveCommunicationType",
      "fetchAvailableFields",
    ]),
    resetForm() {
      this.communicationType = cloneDeep(this.origin);
    },
    fetchItem() {
      this.fetchCommunicationTypeById(parseInt(this.id ?? ""))
        .then((result) => {
          this.communicationType = result.data;
          this.origin = cloneDeep(result.data);
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    triggerUpdate(e: any) {
      if (this.communicationType == null) return;
      let formData = e.target.elements;
      let updateCommunicationType: UpdateCommunicationTypeViewModel = {
        id: this.communicationType.id,
        type: formData.communicationType.value,
        fields: this.communicationType.fields,
      };
      this.status = "loading";
      this.updateActiveCommunicationType(updateCommunicationType)
        .then(() => {
          this.fetchItem();
          this.status = { status: "success" };
        })
        .catch((err) => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
