<template>
  <MainTemplate :useStagedOverviewLink="false">
    <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">Administration übertragen</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 class="flex flex-col gap-4 py-2 w-full max-w-xl mx-auto" @submit.prevent="triggerTransfer">
        <div class="w-full">
          <Combobox v-model="selected">
            <ComboboxLabel>Nutzer suchen</ComboboxLabel>
            <div class="relative mt-1">
              <ComboboxInput
                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"
                :displayValue="(person) => person.firstname + ' ' + person.lastname"
                @input="query = $event.target.value"
              />
              <ComboboxButton class="absolute inset-y-0 right-0 flex items-center pr-2">
                <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
              </ComboboxButton>
              <TransitionRoot
                leave="transition ease-in duration-100"
                leaveFrom="opacity-100"
                leaveTo="opacity-0"
                @after-leave="query = ''"
              >
                <ComboboxOptions
                  class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-md ring-1 ring-black/5 focus:outline-none sm:text-sm"
                >
                  <ComboboxOption v-if="filtered.length === 0" as="template" disabled>
                    <li class="text-text relative cursor-default select-none py-2 pl-3 pr-4">
                      <span class="font-normal block truncate">Keine Auswahl</span>
                    </li>
                  </ComboboxOption>

                  <ComboboxOption
                    v-for="user in filtered"
                    as="template"
                    :key="user.id"
                    :value="user"
                    v-slot="{ selected, active }"
                  >
                    <li
                      class="relative cursor-default select-none py-2 pl-10 pr-4"
                      :class="{
                        'bg-primary text-white': active,
                        'text-gray-900': !active,
                      }"
                    >
                      <span class="block truncate" :class="{ 'font-medium': selected, 'font-normal': !selected }">
                        {{ user.firstname }} {{ user.lastname }} {{ user.nameaffix }}
                      </span>
                      <span
                        v-if="selected"
                        class="absolute inset-y-0 left-0 flex items-center pl-3"
                        :class="{ 'text-white': active, 'text-primary': !active }"
                      >
                        <CheckIcon class="h-5 w-5" aria-hidden="true" />
                      </span>
                    </li>
                  </ComboboxOption>
                </ComboboxOptions>
              </TransitionRoot>
            </div>
          </Combobox>
        </div>
        <div class="flex flex-row justify-end gap-2">
          <button primary-outline type="reset" class="!w-fit" @click="selected = undefined">abbrechen</button>
          <button primary type="submit" class="!w-fit" :disabled="status == 'loading' || selected == undefined">
            übertragen
          </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, markRaw, defineAsyncComponent } from "vue";
import { mapActions, mapState } 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 { useUserStore } from "@/stores/admin/user";
import { isAuthenticatedPromise } from "@/router/authGuard";
import {
  Combobox,
  ComboboxLabel,
  ComboboxInput,
  ComboboxButton,
  ComboboxOptions,
  ComboboxOption,
  TransitionRoot,
} from "@headlessui/vue";
import { CheckIcon, ChevronUpDownIcon } from "@heroicons/vue/20/solid";
import type { UserViewModel } from "@/viewmodels/admin/user.models";
</script>

<script lang="ts">
export default defineComponent({
  data() {
    return {
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      query: "" as String,
      selected: undefined as UserViewModel | undefined,
    };
  },
  computed: {
    ...mapState(useUserStore, ["users", "loading"]),
    filtered(): Array<UserViewModel> {
      return this.query === ""
        ? this.users
        : this.users.filter((user) =>
            (user.firstname + " " + user.lastname)
              .toLowerCase()
              .replace(/\s+/g, "")
              .includes(this.query.toLowerCase().replace(/\s+/g, ""))
          );
    },
    sorted(): Array<MemberViewModel> {
      return this.selected.sort((a, b) => {
        if (a.lastname < b.lastname) return -1;
        if (a.lastname > b.lastname) return 1;
        if (a.firstname < b.firstname) return -1;
        if (a.firstname > b.firstname) return 1;
        return 0;
      });
    },
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    ...mapActions(useUserStore, ["fetchUsers"]),
    triggerTransfer(e: any) {
      if (this.selected == undefined) return;
      this.status = "loading";
      this.$http
        .put(`/user/transferOwner`, {
          toId: this.selected.id,
        })
        .then(() => {
          isAuthenticatedPromise(true).catch(() => {});
          this.status = { status: "success" };
          setTimeout(() => {
            this.$router.push({ name: "account-default" });
          }, 2000);
        })
        .catch((err) => {
          this.status = { status: "failed" };
        });
    },
  },
});
</script>
