<template>
  <v-autocomplete
    ref="userSearchInput"
    :value="value"
    :rules="rules"
    :items="users"
    :loading="isLoading"
    :search-input.sync="usersQuery"
    :label="label"
    :hint="hint"
    chips
    hide-no-data
    hide-selected
    no-filter
    item-text="username"
    item-value="email"
    @input="onSelect">

    <template
      slot="selection"
      slot-scope="{ item, selected }">
      <v-chip
        :selected="selected"
        close
        class="chip--select-multi"
        @input="remove">
        <v-avatar>
          <img :src="item.profile">
        </v-avatar>
        {{ item.username }}
      </v-chip>
    </template>

    <template
      slot="item"
      slot-scope="{ item }">
      <template>
        <v-list-tile-avatar v-if="item.profile">
          <img :src="item.profile">
        </v-list-tile-avatar>
        <v-list-tile-content>
          <v-list-tile-title v-html="item.username"/>
          <v-list-tile-sub-title v-html="item.email"/>
        </v-list-tile-content>
      </template>
    </template>
  </v-autocomplete>
</template>

<script>
import { fetchListRecords } from '@/utils/api'
import { profileUrl } from '@/utils/helpers'

export default {
  name: 'UserSearchInput',
  props: {
    value: String,
    rules: Array,
    label: String,
    hint: String
  },
  data () {
    return {
      isLoading: false,
      usersQuery: '',
      data: null,
      users: []
    }
  },
  watch: {
    usersQuery (value) {
      this.searchUsers(value)
    }
  },
  methods: {
    async searchUsers (value) {
      if (value) {
        this.isLoading = true
        const response = await fetchListRecords('users', {
          search: value,
          limit: 5
        })
        let users = response.results
        if (!users.length) {
          users = [{
            header: 'Add new user by email'
          }, {
            username: value.split('@')[0],
            email: value
          }]
        }
        this.updateUsers(users)
        this.isLoading = false
      }
    },
    updateUsers (users) {
      this.users = users.map(user => {
        user.profile = profileUrl(user)
        return user
      })
    },
    onSelect (value) {
      this.$emit('input', value)
    },
    remove () {
      this.$refs.userSearchInput.reset()
    }
  }
}
</script>
