<template>
  <div class="flex flex-col gap-2 h-full w-full overflow-y-auto">
    <Spinner v-if="loadingActive == 'loading'" class="mx-auto" />
    <p v-else-if="loadingActive == 'failed'" @click="" class="cursor-pointer">&#8634; laden fehlgeschlagen</p>
    <div class="w-full">
      <Combobox v-model="selected" multiple>
        <div class="relative mt-1">
          <ComboboxLabel>Anwesende suchen</ComboboxLabel>
          <div
            class="relative w-full cursor-default overflow-hidden rounded-lg bg-white text-left shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-white/75 focus-visible:ring-offset-2 focus-visible:ring-offset-teal-300 sm:text-sm"
          >
            <ComboboxInput
              class="w-full border-none py-2 pl-3 pr-10 text-sm leading-5 text-gray-900 focus:ring-0"
              @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>
          </div>
          <TransitionRoot
            leave="transition ease-in duration-100"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
            @after-leave="query = ''"
          >
            <ComboboxOptions
              class="absolute mt-1 max-h-60 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"
            >
              <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="member in filtered"
                as="template"
                :key="member.id"
                :value="member"
                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 }">
                    {{ member.firstname }} {{ member.lastname }} {{ member.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>
    <br />
    <p>Ausgewählte Anwesende</p>
    <div class="flex flex-col gap-2 grow overflow-y-auto">
      <div
        v-for="member in selected"
        :key="member.id"
        class="flex flex-row h-fit w-full border border-primary rounded-md bg-primary p-2 text-white justify-between items-center"
      >
        <p>{{ member.lastname }}, {{ member.firstname }} {{ member.nameaffix ? `- ${member.nameaffix}` : "" }}</p>
        <TrashIcon class="w-5 h-5 p-1 box-content cursor-pointer" @click="removeSelected(member.id)" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapActions, mapState } from "pinia";
import Spinner from "@/components/Spinner.vue";
import {
  Combobox,
  ComboboxLabel,
  ComboboxInput,
  ComboboxButton,
  ComboboxOptions,
  ComboboxOption,
  TransitionRoot,
} from "@headlessui/vue";
import { CheckIcon, ChevronUpDownIcon } from "@heroicons/vue/20/solid";
import { TrashIcon } from "@heroicons/vue/24/outline";
import { useProtocolStore } from "@/stores/admin/protocol";
import { useMemberStore } from "@/stores/admin/member";
import type { MemberViewModel } from "@/viewmodels/admin/member.models";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    protocolId: String,
  },
  data() {
    return {
      query: "" as String,
      selected: [] as Array<MemberViewModel>,
    };
  },
  computed: {
    ...mapState(useProtocolStore, ["loadingActive"]),
    ...mapState(useMemberStore, ["members"]),
    filtered(): Array<MemberViewModel> {
      return this.query === ""
        ? this.members
        : this.members.filter((member) =>
            (member.firstname + " " + member.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.fetchMembers();
  },
  methods: {
    ...mapActions(useMemberStore, ["fetchMembers"]),
    removeSelected(id: number) {
      let index = this.selected.findIndex((s) => s.id == id);
      if (index != -1) {
        this.selected.splice(index, 1);
      }
    },
  },
});
</script>
