<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 by="memberId">
        <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.memberId"
                :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 }">
                    {{ getMember(member.memberId)?.firstname }} {{ getMember(member.memberId)?.lastname }}
                    {{ getMember(member.memberId)?.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>Anwesenheit</p>
    <div class="flex flex-col gap-2 grow overflow-y-auto">
      <div
        v-for="member in presence"
        :key="member.memberId"
        class="flex flex-row h-fit w-full border border-primary rounded-md bg-primary p-2 text-white justify-between items-center"
      >
        <div class="flex flex-col items-start">
          <p>
            {{ getMember(member.memberId)?.lastname }}, {{ getMember(member.memberId)?.firstname }}
            {{ getMember(member.memberId)?.nameaffix ? `- ${getMember(member.memberId)?.nameaffix}` : "" }}
          </p>
          <div class="flex flex-row gap-4">
            <label class="flex flex-row gap-2 items-center">
              <input type="checkbox" v-model="member.absent" />
              war abwesend
            </label>
            <label v-if="member.absent" class="flex flex-row gap-2 items-center">
              <input type="checkbox" v-model="member.excused" />
              ist entschuldigt
            </label>
          </div>
        </div>
        <TrashIcon
          v-if="can('create', 'club', 'protocol')"
          class="w-5 h-5 p-1 box-content cursor-pointer"
          @click="removeSelected(member.memberId)"
        />
      </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/club/protocol/protocol";
import { useMemberStore } from "@/stores/admin/club/member/member";
import type { MemberViewModel } from "@/viewmodels/admin/club/member/member.models";
import { useProtocolPresenceStore } from "@/stores/admin/club/protocol/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<{ memberId: number; absent: boolean; excused: boolean; protocolId: number }> {
      return (
        this.query === ""
          ? this.members
          : this.members.filter((member) =>
              (member.firstname + " " + member.lastname)
                .toLowerCase()
                .replace(/\s+/g, "")
                .includes(this.query.toLowerCase().replace(/\s+/g, ""))
            )
      ).map((m) => ({ memberId: m.id, absent: false, excused: true, protocolId: parseInt(this.protocolId ?? "") }));
    },
    getMember() {
      return (memberId: number) => {
        return this.members.find((m) => memberId == 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.memberId == id);
      if (index != -1) {
        this.presence.splice(index, 1);
      }
    },
  },
});
</script>
