<template>
  <div class="flex flex-col gap-2 h-full w-full overflow-y-auto">
    <Spinner v-if="loading == 'loading'" class="mx-auto" />
    <p v-else-if="loading == 'failed'">laden fehlgeschlagen</p>
    <form
      v-else-if="member != null"
      class="flex flex-col gap-4 py-2 w-full max-w-xl mx-auto"
      @submit.prevent="triggerUpdate"
    >
      <p class="mx-auto">Mitglied bearbeiten</p>
      <div>
        <Listbox v-model="member.salutation" name="salutation" by="id">
          <ListboxLabel>Anrede</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"> {{ member.salutation.salutation }}</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="salutation in salutations"
                  :key="salutation.id"
                  :value="salutation"
                  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']">{{
                      salutation.salutation
                    }}</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>
        <label for="firstname">Vorname</label>
        <input type="text" id="firstname" required v-model="member.firstname" />
      </div>
      <div>
        <label for="lastname">Nachname</label>
        <input type="text" id="lastname" required v-model="member.lastname" />
      </div>
      <div>
        <label for="nameaffix">Nameaffix (optional)</label>
        <input type="text" id="nameaffix" v-model="member.nameaffix" />
      </div>
      <div>
        <label for="birthdate">Geburtsdatum</label>
        <input type="date" id="birthdate" required v-model="member.birthdate" />
      </div>
      <div>
        <label for="internalId">Interne ID (optional)</label>
        <input type="text" id="internalId" v-model="member.internalId" />
      </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>
  </div>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapActions, mapState } from "pinia";
import MainTemplate from "@/templates/Main.vue";
import { useMemberStore } from "@/stores/admin/club/member/member";
import type { MemberViewModel, UpdateMemberViewModel } from "@/viewmodels/admin/club/member/member.models";
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 cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";
import { useSalutationStore } from "../../../../stores/admin/settings/salutation";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    memberId: String,
  },
  watch: {
    loadingActive() {
      if (this.loading == "loading") {
        this.loading = this.loadingActive;
      }
      if (this.loadingActive == "fetched") this.member = cloneDeep(this.activeMemberObj);
    },
  },
  data() {
    return {
      loading: "loading" as "loading" | "fetched" | "failed",
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      member: null as null | MemberViewModel,
      timeout: null as any,
    };
  },
  computed: {
    canSaveOrReset(): boolean {
      return isEqual(this.activeMemberObj, this.member);
    },
    ...mapState(useMemberStore, ["activeMemberObj", "loadingActive"]),
    ...mapState(useSalutationStore, ["salutations"]),
  },
  mounted() {
    this.fetchItem();
    this.fetchSalutations();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useMemberStore, ["fetchMemberByActiveId", "updateActiveMember"]),
    ...mapActions(useSalutationStore, ["fetchSalutations"]),
    resetForm() {
      this.member = cloneDeep(this.activeMemberObj);
    },
    fetchItem() {
      this.fetchMemberByActiveId();
    },
    triggerUpdate(e: any) {
      if (this.member == null) return;
      let formData = e.target.elements;
      let updateMember: UpdateMemberViewModel = {
        id: this.member.id,
        salutationId: formData["salutation[id]"].value,
        firstname: formData.firstname.value,
        lastname: formData.lastname.value,
        nameaffix: formData.nameaffix.value,
        birthdate: formData.birthdate.value,
        internalId: formData.internalId.value,
      };
      this.status = "loading";
      this.updateActiveMember(updateMember)
        .then(() => {
          this.fetchItem();
          this.status = { status: "success" };
        })
        .catch((err) => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
