<template>
  <div
    :class="{
      'opacity-50': disabled,
    }"
    :style="disabled ? 'pointer-events: none;' : ''"
  >
    <pick-entity
      uniqid="ticket-addressee-selector"
      :types="['user', 'user_group']"
      :picked="selectedEntities"
      :suggested="suggestedValues"
      :multiple="true"
      :removable-if-set="true"
      :display-picked="true"
      :label="label"
      @add-new-entity="addNewEntity"
      @remove-entity="removeEntity"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits } from "vue";

// Components
import PickEntity from "ChillMainAssets/vuejs/PickEntity/PickEntity.vue";

// Types
import { Entities, EntitiesOrMe } from "ChillPersonAssets/types";

// Translations
import {
  CHILL_TICKET_TICKET_ADD_ADDRESSEE_USER_LABEL,
  trans,
} from "translator";

const props = withDefaults(
  defineProps<{
    modelValue: Entities[];
    suggested: Entities[];
    label?: string;
    disabled?: boolean;
  }>(),
  {
    label: trans(CHILL_TICKET_TICKET_ADD_ADDRESSEE_USER_LABEL),
    disabled: false,
  },
);

const emit = defineEmits<(e: "update:modelValue", value: Entities[]) => void>();

const selectedEntities = ref<Entities[]>([...props.modelValue]);
const suggestedValues = ref<Entities[]>([...props.suggested]);
watch(
  () => [props.suggested, props.modelValue],
  () => {
    // Mise à jour des entités sélectionnées
    selectedEntities.value = [...(props.modelValue as Entities[])];

    // Filtrage des suggestions
    suggestedValues.value = props.suggested.filter((suggested: Entities) => {
      return !props.modelValue.some((selected: Entities) => {
        if (suggested.type == "user_group" && selected.type == "user_group") {
          switch (selected.excludeKey) {
            case "level":
              return suggested.excludeKey === "level";
            case "":
              return (
                suggested.excludeKey === "" && suggested.id === selected.id
              );
            default:
              return false;
          }
        } else {
          return (
            suggested.type === selected.type && suggested.id === selected.id
          );
        }
      });
    });
  },
  { immediate: true, deep: true },
);

function addNewEntity({ entity }: { entity: EntitiesOrMe }) {
  selectedEntities.value.push(entity as Entities);
  emit("update:modelValue", selectedEntities.value);
}

function removeEntity({ entity }: { entity: EntitiesOrMe }) {
  const index = selectedEntities.value.findIndex(
    (selectedEntity: Entities) => selectedEntity === entity,
  );
  if (index !== -1) {
    selectedEntities.value.splice(index, 1);
  }
  emit("update:modelValue", selectedEntities.value);
}
</script>
