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

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

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

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

const props = withDefaults(
  defineProps<{
    modelValue: EntitiesOrMe[] | EntitiesOrMe | null;
    suggested: Entities[];
    multiple: boolean;
    types: EntityType[];
    label: string;
    disabled?: boolean;
  }>(),
  {
    disabled: false,
  },
);

const emit = defineEmits<{
  "update:modelValue": [value: EntitiesOrMe[] | EntitiesOrMe | null];
}>();

const multiple = props.multiple;
const types = props.types;
const label = props.label;

const selectedEntities = ref<Entities[]>(
  multiple
    ? [...((props.modelValue as Entities[]) || [])]
    : props.modelValue
      ? [props.modelValue as Entities]
      : [],
);
const suggestedValues = ref<Entities[]>([...props.suggested]);

// Entités sélectionnées pour le composant PickEntity
const pickedEntities = computed(() =>
  multiple ? selectedEntities.value : selectedEntities.value.slice(0, 1),
);

watch(
  () => [props.suggested, props.modelValue],
  () => {
    // Mise à jour des entités sélectionnées
    selectedEntities.value = multiple
      ? [...((props.modelValue as Entities[]) || [])]
      : props.modelValue
        ? [props.modelValue as Entities]
        : [];

    // Filtrage des suggestions
    if (multiple) {
      suggestedValues.value = props.suggested.filter(
        (suggested: Entities) =>
          !(props.modelValue as Entities[])?.some(
            (selected: Entities) =>
              suggested.id === selected.id && suggested.type === selected.type,
          ),
      );
    } else {
      const currentEntity = props.modelValue as Entities | null;
      suggestedValues.value = props.suggested.filter(
        (suggested: Entities) =>
          !(
            currentEntity &&
            suggested.id === currentEntity.id &&
            suggested.type === currentEntity.type
          ),
      );
    }
  },
  { immediate: true, deep: true },
);

function addNewEntity({ entity }: { entity: EntitiesOrMe }) {
  if (multiple) {
    selectedEntities.value.push(entity as Entities);
    emit("update:modelValue", selectedEntities.value);
  } else {
    selectedEntities.value = [entity as Entities];
    emit("update:modelValue", entity);
  }
}

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

<style scoped lang="scss">
ul.person-list {
  list-style-type: none;

  & > li {
    display: inline-block;
    border: 1px solid transparent;
    border-radius: 6px;

    button.remove-person {
      opacity: 10%;
    }
  }

  & > li:hover {
    border: 1px solid white;

    button.remove-person {
      opacity: 100%;
    }
  }
}
</style>
