<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'" @click="fetchProtocolPresence" class="cursor-pointer">
      &#8634; laden fehlgeschlagen
    </p>

    <div class="w-full">
      <Combobox v-model="presence" :disabled="!can('create', 'club', 'protocol')" multiple>
        <ComboboxLabel>Anwesende 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"
            @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 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="member in filtered"
                as="template"
                :key="member.id"
                :value="member.id"
                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
          v-if="can('create', 'club', 'protocol')"
          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, mapWritableState } 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";
import { useProtocolPresenceStore } from "@/stores/admin/protocolPresence";
import { useAbilityStore } from "@/stores/ability";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    protocolId: String,
  },
  data() {
    return {
      query: "" as String,
    };
  },
  computed: {
    ...mapWritableState(useProtocolPresenceStore, ["presence", "loading"]),
    ...mapState(useMemberStore, ["members"]),
    ...mapState(useAbilityStore, ["can"]),
    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;
      });
    },
    selected(): Array<MemberViewModel> {
      return this.members.filter((m) => this.presence.includes(m.id));
    },
  },
  mounted() {
    this.fetchMembers(0, 1000, true);
    this.fetchProtocolPresence();
  },
  methods: {
    ...mapActions(useMemberStore, ["fetchMembers"]),
    ...mapActions(useProtocolPresenceStore, ["fetchProtocolPresence"]),
    removeSelected(id: number) {
      let index = this.presence.findIndex((s) => s == id);
      if (index != -1) {
        this.presence.splice(index, 1);
      }
    },
  },
});
</script>
