<template>
  <div class="flex flex-col gap-2">
    <div class="flex flex-row gap-2 items-center">
      <p>Eingesetztes Material</p>
      <PlusCircleIcon v-if="enabled" class="w-5 h-5 cursor-pointer" @click="showAddForm = !showAddForm" />
    </div>
    <div v-if="showAddForm" class="flex flex-row gap-2 items-center">
      <EquipmentSelect
        title="Ausrüstung wählen"
        usePlaceholder
        :availableEquipment="filteredAvailableEquipments"
        @update:model-value="(v) => addEquipment(v)"
      />
      <XMarkIcon class="w-5 h-5 cursor-pointer" @click="showAddForm = false" />
    </div>

    <DetailFormEquipmentItem
      v-for="[key, equipment] in equipments"
      :key="key"
      :equipmentId="key"
      :equipment="equipment"
      :awareness="awareness"
      :enabled="enabled"
      @remove="removeEquipment(key)"
    />
  </div>
</template>

<script setup lang="ts">
import { defineComponent, type PropType } from "vue";
import * as Y from "yjs";
import { Awareness } from "@/helpers/awareness";
import DetailFormEquipmentItem from "./DetailFormEquipmentItem.vue";
import { PlusCircleIcon, XMarkIcon } from "@heroicons/vue/24/outline";
import { mapState } from "pinia";
import { useEquipmentStore } from "@/stores/admin/configuration/equipment";
import EquipmentSelect from "../../EquipmentSelect.vue";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    map: {
      type: Object as PropType<Y.Map<Y.Map<number | string>>>,
      required: true,
    },
    awareness: {
      type: Object as PropType<Awareness>,
      required: true,
    },
    enabled: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      showAddForm: false as boolean,
    };
  },
  computed: {
    ...mapState(useEquipmentStore, ["availableEquipments"]),
    equipments() {
      return Array.from(this.map.entries());
    },
    filteredAvailableEquipments() {
      let added = Array.from(this.map.keys());
      return this.availableEquipments.filter((av) => !added.includes(av.id));
    },
  },
  methods: {
    addEquipment(equipmentId: string) {
      if (this.map.has(equipmentId)) return;
      this.map.set(equipmentId, new Y.Map<string | number>());
      this.showAddForm = false;
    },
    removeEquipment(equipmentId: string) {
      this.map.delete(equipmentId);
    },
  },
});
</script>
