<template>
  <v-container>
    <v-layout row wrap class="search-input">
      <v-flex xs12 d-inline-flex class="search-btn">
        <v-btn
          fab
          small
          color="primary"
          class="table-action-btn search-flat-btn"
          @mouseenter="showInput">
          <v-icon
            class="white--text text--darken-1">
            search
          </v-icon>
        </v-btn>
        <transition name="slide-fade">
          <v-form v-show="isInputShown" @submit.prevent="search">
            <v-text-field
              ref="input"
              v-model="inputText"
              :label="placeholder"
              :autofocus="enableHotKey"
              class="mt-1"
              light
              hide-details
              single-line
              @keyup.esc="clearText"
              @blur="hideInput"/>
          </v-form>
        </transition>
      </v-flex>
    </v-layout>
  </v-container>
</template>

<script>
import Vue from 'vue'
import _ from 'lodash'

export default {
  name: 'SearchInput',
  props: {
    placeholder: {
      type: String,
      default: 'Search'
    },
    searchText: {
      type: String,
      default: ''
    },
    enableHotKey: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      inputText: this.searchText,
      isInputShown: !!this.searchText
    }
  },
  computed: {
    isFocused () {
      return this.$refs.input.$el.classList.contains('v-input--is-focused')
    },
    keymap () {
      return this.enableHotKey ? { 'ctrl+s': this.showInput } : {}
    }
  },
  watch: {
    inputText () {
      if (this.inputText) {
        this.isInputShown = true
      }
      if (!this.inputText && !this.isFocused) {
        this.isInputShown = false
      }
      this.debouncedEmit()
    },
    searchText () {
      this.inputText = this.searchText
    }
  },
  created () {
    this.debouncedEmit = _.debounce(this.search, 300)
  },
  methods: {
    clearText () {
      this.inputText = undefined
    },
    search () {
      this.$emit('change-search-text', this.inputText)
    },
    showInput () {
      this.isInputShown = true
      if (this.isInputShown) {
        Vue.nextTick(() => Vue.nextTick(() => this.$refs.input.focus()))
      }
    },
    hideInput () {
      if (!this.inputText) {
        this.isInputShown = false
      }
    }
  }
}
</script>

<style lang="scss">
.search-flat-btn {
  margin-bottom: -10px;
  margin-top: 5px;
  margin-left: -4px;
}
.slide-fade-enter-active, .slide-fade-leave-active {
  transition: all .3s ease;
}
.slide-fade-enter, .slide-fade-leave-to {
  transform: translateX(-30px);
  opacity: 0;
}
.search-input {
  height: 32px;
  .v-text-field input {
    padding: 5px 0px;
  }
}
</style>
