<template>
  <div>
    <div
      v-if="$slots.label || label || $slots.labelIcon || labelIcon"
      class="flex"
    >
      <div class="vc-selectbox__label mb-2">
        <label class="vc-selectbox__label-wrapper items-center">
          <span
            class="vc-selectbox__label-wrapper--left-item"
          >
            <slot
              name="labelIcon"
            >
              <i
                v-if="labelIcon"
                :class="labelIcon"
                class="icon-lg vc-selectbox__label-wrapper--left-item-icon text-icons"
              />
            </slot>
          </span>
          <span class="vc-selectbox__label-wrapper-label">
            <span v-if="label">{{ label }} </span>
            <span
              v-if="required"
              class="vc-selectbox__label-wrapper-label__required-icon ml-1"
            >*</span>
          </span>
          <VcPopover
            v-if="infoText || $slots['info-text']"
            :popover-width="infoTooltipWidth"
            arrow-position="bottom-center"
          >
            <template #reference>
              <span class="vc-input__label-info px-1 flex items-center">
                <i class="vc-icon-info icon-base" />
              </span>
            </template>
            <div
              class="label-info-text p-2 text-xs"
            >
              <slot name="info-text">
                {{ infoText }}
              </slot>
            </div>
          </VcPopover>
        </label>
      </div>
    </div>
    <div
      class="vc-selectbox-input__container"
      :class="{
        'disabled': disabled,
        'vc-selectbox--prefix-icon': prefixIcon,
        'vc-selectbox--error': error
      }"
    >
      <input
        :value="modelValue"
        :class="{
          'cursor-pointer': readonly,
          'vc-input--error': error
        }"
        :data-test="dataTestName"
        :disabled="disabled"
        :placeholder="customPlaceholder"
        :readonly="readonly"
        :style="[darkPlaceholderColor ? '--placeholder-color: text-default-color' : '', styles]"
        autocomplete="off"
        type="text"
        class="vc-selectbox"
        @change="onChange"
        @input="onInput"
        @click="onClick"
        @keyup.down="onArrowDown"
        @keyup.up="onArrowUp"
        @keyup.enter="onEnter"
        @keydown.esc.stop.prevent="$emit('onDropdownClose')"
        @focus="onFocus"
        @blur="onBlur"
      >
      <div
        v-if="prefixIcon"
        class="vc-selectbox__prefix-icon"
      >
        <i
          class="cursor-pointer"
          :class="prefixClasses"
          :style="prefixStyle"
        />
      </div>
      <span
        v-if="!disabled"
      >
        <span
          v-if="hasSuffixContentSlot"
          ref="suffix-content"
          class="vc-input-suffix-content"
          @click="onClick"
        >
          <slot name="suffix-content" />
        </span>
        <span
          class="vc-input-suffix"
        >
          <i
            v-if="selectedValue && clearable"
            class="vc-icon-close icon-xs icon cursor-pointer"
            @click="onClear"
          />
          <i
            v-else
            class="vc-icon-down icon-lg icon cursor-pointer"
            :class="{ rotate: open }"
            @click="onClick"
          />
        </span>
      </span>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { debounce } from '@/utils/debounce'
import inputMixin from '@/mixins/input.mixin'
import selectBoxMixin from '@/mixins/selectBox.mixin'
export default defineComponent({
  name: 'VcSelectbox',
  mixins: [inputMixin, selectBoxMixin],
  props: {
    selectedValue: {
      type: [String, Number],
      default: ''
    },
    config: {
      type: Object,
      default: () => ({})
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'onclick', 'onblur', 'onchange', 'onclear', 'onfocus', 'onArrowDown', 'onArrowUp',
    'onEnter', 'onDropdownClose'],
  data () {
    return {
      styles: {
        '--selectbox-padding': '25px' as string | undefined
      }
    }
  },
  computed: {
    hasSuffixContentSlot () {
      return !!this.$slots['suffix-content']
    }
  },
  watch: {
    selectedValue: {
      immediate: true,
      handler (newVal): void {
        if (newVal) {
          this.$emit('update:modelValue', '')
          this.customPlaceholder = newVal
          this.darkPlaceholderColor = true
        } else {
          this.customPlaceholder = this.placeholder
        }
      }
    }
  },
  mounted () {
    this.onInput = debounce(this.onInput, 500)
    if (this.hasSuffixContentSlot) {
      this.$nextTick(() => {
        const element = this.$refs['suffix-content'] as HTMLElement
        if (element?.offsetWidth) {
          const arrowContainerWidth = 24
          const additionalSpaceBeforeSuffixSlot = 10
          const paddingValue = arrowContainerWidth + element.offsetWidth + additionalSpaceBeforeSuffixSlot
          this.styles = {
            '--selectbox-padding': `${paddingValue}px`
          }
        }
      })
    }
  },
  methods: {
    onBlur (): void {
      if (this.selectedValue) {
        this.darkPlaceholderColor = true
      }
      this.$emit('onblur')
    }
  }
})
</script>
<style lang="scss" scoped>
@import "VcSelectbox";
</style>
