<template>
  <div class="w-full md:max-w-md">
    <div class="flex flex-col items-center">
      <p class="text-xl font-medium">Gerät aktualisieren</p>
    </div>
    <br />
    <Spinner v-if="loading == 'loading' && equipment == null" class="mx-auto" />
    <p v-else-if="loading == 'failed'" @click="fetchItem" class="cursor-pointer">&#8634; laden fehlgeschlagen</p>
    <form v-if="equipment" class="flex flex-col gap-4 py-2" @submit.prevent="triggerUpdate">
      <div>
        <label for="name">Bezeichnung</label>
        <input type="text" id="name" required v-model="equipment.name" />
      </div>
      <div>
        <label for="code">Code (optional)</label>
        <input type="text" id="code" v-model="equipment.code" />
      </div>
      <div>
        <label for="type">Typ (optional)</label>
        <input type="text" id="type" v-model="equipment.type" />
      </div>
      <div>
        <label for="commissioned">verfügbar ab (optional)</label>
        <input type="date" id="commissioned" v-model="equipment.commissioned" />
      </div>
      <div>
        <label for="decommissioned">verfügbar bis (optional)</label>
        <input type="date" id="decommissioned" v-model="equipment.decommissioned" />
      </div>
      <div class="flex flex-row gap-2">
        <button primary-outline type="reset" :disabled="canSaveOrReset" @click="resetForm">verwerfen</button>
        <button primary type="submit" :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>

    <div class="flex flex-row justify-end">
      <div class="flex flex-row gap-4 py-2">
        <button primary-outline @click="closeModal" :disabled="status == 'loading' || status?.status == 'success'">
          schließen
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapState, mapActions } from "pinia";
import { useModalStore } from "@/stores/modal";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
import { Listbox, ListboxButton, ListboxOptions, ListboxOption, ListboxLabel } from "@headlessui/vue";
import { CheckIcon, ChevronUpDownIcon } from "@heroicons/vue/20/solid";
import { useEquipmentStore } from "@/stores/admin/configuration/equipment";
import type {
  CreateEquipmentViewModel,
  EquipmentViewModel,
  UpdateEquipmentViewModel,
} from "@/viewmodels/admin/configuration/equipment.models";
import isEqual from "lodash.isequal";
import cloneDeep from "lodash.clonedeep";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    data: { type: String, default: "" },
  },
  data() {
    return {
      loading: "loading" as "loading" | "fetched" | "failed",
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      equipment: null as null | EquipmentViewModel,
      origin: null as null | EquipmentViewModel,
      timeout: null as any,
    };
  },
  computed: {
    canSaveOrReset(): boolean {
      return isEqual(this.origin, this.equipment);
    },
  },
  mounted() {
    this.fetchItem();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useModalStore, ["closeModal"]),
    ...mapActions(useEquipmentStore, ["updateEquipment", "fetchEquipmentById"]),
    resetForm() {
      this.equipment = cloneDeep(this.origin);
    },
    fetchItem() {
      this.loading = "loading";
      this.fetchEquipmentById(this.data)
        .then((res) => {
          this.loading = "fetched";
          this.origin = res.data;
          this.equipment = cloneDeep(this.origin);
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    triggerUpdate(e: any) {
      let formData = e.target.elements;
      let updateEquipment: UpdateEquipmentViewModel = {
        id: this.data,
        code: formData.code.value,
        type: formData.type.value,
        name: formData.name.value,
        commissioned: formData.commissioned.value,
        decommissioned: formData.decommissioned.value,
      };
      this.status = "loading";
      this.updateEquipment(updateEquipment)
        .then(() => {
          this.fetchItem();
          this.status = { status: "success" };
        })
        .catch(() => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
