<template>
  <VAutocomplete
    v-model="filterModel"
    clearable
    outlined
    dense
    hideDetails
    returnObject
    multiple
    chips
    smallChips
    deletableChips
    :no-data-text="$t('No data available')"
    :menuProps="{ offsetY: true }"
    :items="filterItems"
    :label="$t(filter.name)"
    @focus="applyMargin ? onFocus : {}"
    @blur="applyMargin ? onBlur : {}"
  >
    <template #selection="{ item, index, select, selected, disabled }">
      <VChip
        small
        close
        class="custom-filter-chip"
        :input-value="selected"
        :disabled="disabled"
        @click="select"
        @click:close="filterModel.splice(index, 1)"
      >
        <span class="custom-filter-chip__text">{{ item.text || item }}</span>
      </VChip>
    </template>
  </VAutocomplete>
</template>

<style>
.custom-filter-chip {
  max-width: 200px;
}
.custom-filter-chip__text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

<script>
import { defineComponent, toRef } from '@vue/composition-api'
import { useCustomFilters } from '@pitcher/core'
import { useKeyboardMarginHelper } from '../../../utils/keyboardMarginHelper'

export default defineComponent({
  name: 'CustomFilter',
  props: {
    filter: {
      type: Object,
      required: true,
    },
    type: {
      type: String,
      required: true,
    },
    applyMargin: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props) {
    const { filterItems, filterModel } = useCustomFilters(props.type, toRef(props, 'filter'))
    const { onFocus, onBlur } = useKeyboardMarginHelper()

    return {
      filterItems,
      filterModel,
      onFocus,
      onBlur,
    }
  },
})
</script>
