<template>
  <div class="input-selector-container">
    <div
      class="input-selector-btn"
      data-bs-toggle="dropdown"
      aria-expanded="false"
      id="input-selector-btn"
    >
      <span>{{ selected || '' }}</span>
      <svg-icon icon="dropdown" class-name="selector-dropdown-icon" />
    </div>
    <ul class="dropdown-menu" aria-labelledby="input-selector-btn">
      <li>
        <button v-if="!inputing" class="btn btn-link dropdown-new" @click="newAction">+ NEW</button>
        <div v-if="inputing" class="dropdown-new-input-container">
          <input type="text" v-model="newval" @keyup.enter="newItemAction" />
          <svg-icon v-if="newval" icon="msg-enter" class-name="dropdown-new-input-icon" />
        </div>
      </li>
      <li v-for="item in selectList" :key="item">
        <button
          class="btn btn-link"
          @click="selectItem(item)"
          :class="item == selected ? 'active' : ''"
        >
          {{ item }}
        </button>
      </li>
    </ul>
  </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon.vue'
export default {
  name: 'InputSelector',
  props: {
    selectList: {
      type: Array,
      default: () => []
    },
    selected: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      inputing: true,
      newval: ''
    }
  },
  mounted() {},
  components: { SvgIcon },
  methods: {
    newAction($event) {
      $event.stopPropagation()
      this.newval = ''
      this.inputing = true
    },
    selectItem(item) {
      this.$emit('selectedChange', { selected: item, isNew: false })
    },
    newItemAction() {
      if (!this.newval) return
      this.$emit('selectedChange', {
        selected: this.newval,
        isNew: this.selectList.indexOf(this.newval) === -1
      })
      this.newval = ''
      this.inputing = false
    }
  }
}
</script>

<style lang="scss">
.input-selector-container {
  width: fit-content;
  height: fit-content;
  position: relative;
  .input-selector-btn {
    width: 153px;
    height: 30px;
    display: flex;
    align-items: center;
    overflow: hidden;
    cursor: pointer;
    border: 1px solid #e7e8eb;
    border-radius: 3px;
    padding: 0 3px 0 5px;
    > span {
      font-size: 18px;
      font-weight: 500;
      color: #242424;
      flex: 1;
      text-align: left;
    }
    .selector-dropdown-icon {
      color: #242424;
      padding: 3px;
    }
  }
}
</style>
