<template>

  <v-autocomplete
    ref="projectSearchInput"
    :value="value"
    :rules="rules"
    :items="items"
    :loading="isLoading"
    :search-input.sync="projectsQuery"
    :label="label"
    :hint="hint"
    chips
    deletable-chips
    hide-selected
    hide-no-data
    no-filter
    return-object
    item-text="pk"
    item-value="pk"
    @input="onSelect">

    <template slot="no-data">
      <v-list-tile>
        <v-list-tile-title>
          Search for an existing
          <strong>Project</strong>
        </v-list-tile-title>
      </v-list-tile>
    </template>

    <template
      slot="selection"
      slot-scope="{ item, selected }">

      <v-chip
        :selected="selected"
        class="chip--select-multi"
        close
        @input="remove">
        <v-avatar
          color="primary"
          class="subheading font-weight-light white--text">
          {{ item.pk }}
        </v-avatar>
        {{ (item.short_title || item.title) | truncate }}
      </v-chip>

    </template>

    <template
      slot="item"
      slot-scope="{ item, tile }">

      <v-list-tile-avatar
        color="primary"
        class="subheading font-weight-light white--text">
        {{ item.pk }}
      </v-list-tile-avatar>

      <v-list-tile-content>
        <v-list-tile-title v-text="item.title"/>
        <v-list-tile-sub-title v-text="item.owner"/>
      </v-list-tile-content>
    </template>

  </v-autocomplete>
</template>

<script>
import { fetchListRecords } from '../../utils/api'

export default {
  name: 'ProjectSearchInput',
  props: {
    value: Object,
    rules: Array,
    label: String,
    hint: String
  },
  data () {
    return {
      isLoading: false,
      projectsQuery: '',
      data: null,
      projects: []
    }
  },
  computed: {
    items () {
      if (this.value && !this.$contains(this.projects, this.value, 'pk')) {
        return [this.value, ...this.projects]
      } else {
        return this.projects
      }
    }
  },
  watch: {
    projectsQuery (value) {
      this.searchProjecs(value)
    }
  },
  methods: {
    async searchProjecs (value) {
      if (value) {
        this.isLoading = true
        const response = await fetchListRecords('projects', {
          search: value,
          limit: 5
        })
        this.projects = response.results
        this.isLoading = false
      }
    },
    onSelect (value) {
      this.$emit('input', value)
    },
    remove () {
      this.$refs.projectSearchInput.reset()
    }
  }
}
</script>

<style lang="scss" scoped>
.v-autocomplete {
  margin-bottom:  10px;
}
</style>
