<template>
  <div class="dynamic-field-dropdown" :style="{ top: `${topOffset}px` }" v-on:click.stop>
    <ul>
      <li v-for="tag in filteredTags" :key="tag.id" v-on:click="select(tag)">
        {{ tag.text }}
        <span class="description">{{ tag.description }}</span>
      </li>
    </ul>
  </div>
</template>

<style lang="scss" scoped>
$lightgrey: #f4f4f4;

.dynamic-field-dropdown {
  position: absolute;
  top: 0;
  left: 0;
  background-color: #fff;
  border-radius: 0.25rem;
  border: 1px solid rgba(0, 0, 0, 0.2);
  z-index: 10;
  max-height: 200px;
  overflow-y: scroll;

  ul {
    list-style-type: none;
    padding: 0;
    margin: 0;

    li {
      padding: 10px 30px;

      .description {
        font-size: 12px;
        display: block;
      }

      &:hover {
        background-color: $lightgrey;
        cursor: pointer;
      }

      &:not(:last-child) {
        border-bottom: 1px solid $lightgrey;
      }
    }
  }
}
</style>

<script>
import { mapState } from 'vuex';

export default {
  name: 'schema-input',
  docs: 'Geeft een lijst met dynamische cms items in de vorm van een dropdown.',
  props: {
    searchValue: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      opened: true,
      topOffset: this.$parent.$el.clientHeight + 5
    };
  },
  computed: {
    ...mapState('data', ['dynamicTags']),
    filteredTags() {
      return this.searchValue ? this.dynamicTags.filter((tag) => tag.text.match(new RegExp(this.searchValue, 'i'))) : this.dynamicTags;
    }
  },
  created() {
    document.addEventListener('click', this.close, false);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.close, false);
  },
  methods: {
    select(tag) {
      this.$emit('select', tag);
    },
    close() {
      this.$emit('close');
    }
  }
};
</script>
