<template>
  <div class="autocomplete">
    <input
      type="search"
      v-model="search"
      @input="onChange"
      class="form-control"
      autocomplete="off"
      onClick="this.select();"
    />
    <ul v-show="isOpen" class="autocomplete-results">
      <li
        v-for="(result, i) in results"
        :key="i"
        class="autocomplete-result"
        @click="setResult(result)"
      >
        {{ result }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    items: {
      type: Array,
      required: false,
      default: () => []
    }
  },
  data() {
    return {
      search: "Search by City or Suburb...",
      results: [],
      isOpen: false
    };
  },
  methods: {
    onChange() {
      if (this.search.length >= 3) {
        this.isOpen = true;
        this.filterResults();
      } else {
        this.isOpen = false;
      }
    },
    filterResults() {
      this.results = this.items.filter(
        item => item.toLowerCase().indexOf(this.search.toLowerCase()) > -1
      );
    },
    setResult(result) {
      this.search = result;
      this.isOpen = false;
      this.$emit("selection", this.search);
    }
  }
};
</script>

<style>
.autocomplete {
  position: relative;
  width: 130px;
}

.autocomplete-results {
  padding: 0;
  margin: 0;
  border: 1px solid #eeeeee;
  height: 120px;
  overflow: auto;
  background-color: white;
}

.autocomplete-result {
  list-style: none;
  text-align: left;
  padding: 4px 2px;
  cursor: pointer;
}

.autocomplete-result:hover {
  background-color: #60cbeb;
  color: white;
}
</style>
