<template>
<div class="container is-paddingless">
  <div class="field has-addons">
    <div class="control is-expanded" 
        :class="{'is-loading': is_loading }">
      <input type="text" 
        v-model="search"
        @input="autoCompletion" 
        class="input" 
       :class="{'is-danger': no_results, 
                'is-warning': auto_open}"
        autocomplete="on">
        </input>
      </div>
    <div class="control">
      <button class="button is-primary"
        :disabled="no_results"
        @click="addItem"
        >+</button>
      </div>
    </div>
    <div class="dropdown" :class="{'is-active': auto_open}">
      <div class="dropdown-menu">
        <div class="dropdown-content">
            <a v-for="(result,i) in results" :key="i"
              @click="setResult(result.name)"
              class="dropdown-item"
              >
              {{ result.name }}
              </a>
            </div>
            </div>
      </div>
  </div>
</template>

<script>
    // List of items for autocomplete
    const MOCK_ITEMS = [
        {id: 35, name: "Cape d'invisibilité", sell_value: 30000}, 
        {id: 8, name: "Arc long", sell_value: 10}, 
    ];
 
    export default {
        data () {
            return {
                is_loading: false,
                no_results: false,
                search: '',
                results: [],
                auto_open: false,
            };
        },
        methods: {
            autoCompletion (ev) {
                // TODO: a lot happens here that
                //       need to be clarified
                if (this.search == '') {
                    this.auto_open = false;
                    this.results = [];
                    this.no_results = false;
                } else {
                    this.results = MOCK_ITEMS.filter(item => {
                        return item.name.includes(this.search);
                    });
                    // Update status 
                    if (this.results.length == 0) {
                        this.no_results = true;
                    } else {
                        this.no_results = false;
                        this.auto_open = true;
                    }
                }
            },
            setResult(result) {
                this.search = result;
                this.auto_open = false;
            },
            addItem () {
                this.$emit("addItem", this.search);        
                this.search = '';
                this.results = [];
                this.no_results = false;
                this.auto_open = false;
            }
        },
    }
</script>

<style scoped>
    .dropdown, .dropdown-menu { min-width: 100%; margin-top: 0; padding-top: 0;}
    .dropdown { top: -0.75rem; }
</style>
