<template>
  <div>
    <div
      v-if="$slots.label || label || $slots.labelIcon || labelIcon"
      class="flex"
    >
      <div class="vc-multiple-selectbox__label mb-2">
        <label class="vc-multiple-selectbox__label-wrapper items-center">
          <span
            class="vc-multiple-selectbox__label-wrapper--left-item"
          >
            <slot
              name="labelIcon"
            >
              <i
                v-if="labelIcon"
                :class="labelIcon"
                class="icon-lg vc-multiple-selectbox__label-wrapper--left-item-icon text-icons"
              />
            </slot>
          </span>
          <span class="vc-multiple-selectbox__label-wrapper-label">
            <span v-if="label">{{ label }} </span>
            <span
              v-if="required"
              class="vc-multiple-selectbox__label-wrapper-label__required-icon ml-1"
            >*</span>
          </span>
        </label>
      </div>
    </div>
    <div class="vc-multiple-selectbox-input-wrapper relative">
      <div
        class="vc-multiple-selectbox-tags w-full px-4 pointer-events-none"
      >
        <VcDelimitedList
          v-if="selectedElementsList.length && (!open || readonly)"
          :list="selectedElementsList"
          :limit="5"
          :open="hiddenItemsPopupOpen"
          trigger="manual"
          separator=""
          @click-outside="onClickOutside"
        >
          <template #list-item="{item}">
            <VcTag
              :label="getOptionLabel(item)"
              :icon="item.icon"
              :max-content="100"
              closable
              class="pointer-events-auto"
              @on-close="onSelectedItemDelete(optionValue(item, config))"
            />
          </template>
          <template #reference="{listLength, items}">
            <VcTag
              class="pointer-events-auto cursor-pointer"
              :label="`+ ${listLength}`"
              closable
              @click="onHiddenItemsTagClick"
              @on-close="onSelectedHiddenItemsDelete(items)"
            />
          </template>
          <template #other-content="{list}">
            <div
              v-for="(item, index) in list"
              :key="index"
              class="flex items-center justify-start p-2"
            >
              <VcTag
                :label="getOptionLabel(item)"
                :icon="optionIcon(item, config)"
                :max-content="180"
                closable
                class="pointer-events-auto"
                @on-close="onSelectedItemDelete(optionValue(item, config))"
              />
            </div>
          </template>
        </VcDelimitedList>
      </div>
      <div
        class="vc-multiple-selectbox-input__container pointer-events-auto"
        :class="{ 'disabled': disabled || (selectedElementsList.length&&!open)}"
        @click.stop="onInputWrapperClick"
      >
        <input
          :value="modelValue"
          :class="{'cursor-pointer': readonly}"
          class="vc-multiple-selectbox"
          type="text"
          :data-test="dataTestName"
          :disabled="disabled"
          :placeholder="!selectedElementsList.length?placeholder:''"
          :readonly="readonly"
          @change="onChange"
          @input="onInput"
          @keyup.down="onArrowDown"
          @keyup.up="onArrowUp"
          @keyup.enter="onEnter"
          @keydown.esc.stop.prevent="$emit('onDropdownClose')"
          @click="onClick"
          @focus="onFocus"
          @blur="onBlur"
        >
        <span
          v-if="!disabled"
          class="vc-input-suffix"
        >
          <i
            class="vc-icon-down icon-lg icon"
            :class="{rotate: open}"
          />
        </span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'
import VcTag from '@/components/VcTag/VcTag.vue'
import { debounce } from '@/utils/debounce'
import inputMixin from '@/mixins/input.mixin'
import selectBoxMixin from '@/mixins/selectBox.mixin'
import { OptionType, OptionValueType } from '@/types/OptionAndConfig.types'
import optionMethods from '@/mixins/optionMethods.mixin'
import VcDelimitedList from '@/components/VcDelimitedList/VcDelimitedList.vue'

export default defineComponent({
  name: 'VcMultipleSelectbox',
  components: {
    VcTag,
    VcDelimitedList
  },
  mixins: [inputMixin, optionMethods, selectBoxMixin],
  props: {
    selectedElementsList: {
      type: Array,
      default: () => []
    },
    optionsList: {
      type: Array as PropType<OptionType[]>,
      default: () => []
    },
    readonly: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:modelValue', 'onclick', 'onblur', 'onchange', 'onclear', 'onfocus', 'onArrowDown', 'onArrowUp',
    'onEnter', 'onDropdownClose', 'onItemDelete', 'onHiddenItemsDelete', 'onInputWrapperClick'],
  data () {
    return {
      hiddenItemsPopupOpen: false as boolean
    }
  },
  mounted () {
    this.onInput = debounce(this.onInput, 500)
  },
  methods: {
    getOptionLabel (item: string) {
      const option = this.optionsList.find((opt) => {
        return this.optionValue(opt, this.config) === item
      })

      return this.optionLabel(option, this.config)
    },
    onClickOutside () {
      this.hiddenItemsPopupOpen = false
    },
    onSelectedItemDelete (id: OptionValueType) {
      this.$emit('onItemDelete', id)
    },
    onSelectedHiddenItemsDelete (items: OptionType[]) {
      this.$emit('onHiddenItemsDelete', items)
    },
    onHiddenItemsTagClick () {
      this.hiddenItemsPopupOpen = !this.hiddenItemsPopupOpen
    },
    onInputWrapperClick (): void {
      if (this.selectedElementsList.length && !this.open) {
        this.$emit('onInputWrapperClick')
      }
    },
    onBlur (): void {
      this.$emit('onblur')
    }
  }
})
</script>
<style lang="scss" scoped>
@import 'src/assets/sass/main/mixins';
.vc-multiple-selectbox{
  @include input;
  &-input__container{
    @apply h-8 relative rounded w-full;
    .vc-multiple-selectbox{
      @apply text-sm pl-3 pr-6 rounded border border-secondary-actions h-full outline-none;
      --placeholder-color: #9EA6B2;
    }
    .vc-multiple-selectbox::placeholder {
      color: var(--placeholder-color);
    }
    .vc-input-suffix{
      @apply absolute flex h-full items-center top-0 right-1 w-6 justify-center;
      .icon {
        @apply text-primary;
        transform: rotate(0deg);
        transition: transform 0.2s ease-in;
      }
      .rotate {
        transform: rotate(180deg);
      }
    }
  }
  &-tags{
    @apply absolute z-1 flex items-center top-2/4;
    transform: translateY(-50%);
    max-width: calc(100% - 24px);

    :deep(.vc-delimited-list-container) {
      display: flex;
    }

    :deep(.vc-delimited-list-item-wrapper) {
      overflow: hidden;
    }

    :deep(.vc-tag) {
      overflow: hidden;
    }

    :deep(.vc-tag--content) {
      overflow: hidden;
    }
  }
}
</style>
