<template>
  <div
    v-click-outside="hide"
    class="search-form-wrapper"
  >
    <div @click="togglePanel">
      <slot />
    </div>

    <transition name="fade">
      <div
        v-if="open"
        class="search-form-panel"
      >
        <input
          ref="search-value"
          v-model="value"
          type="search"
          :placeholder="__('Search')"
          @input="search"
        >

        <ul class="results" v-if="value">
          <div
            v-if="loading"
            class="loading"
          >
            <sync-loader
              :size="10"
              class="spinner"
            />
          </div>
          <li
            v-for="item in results"
            v-else-if="results.length > 0"
            :key="item.id"
          >
            <a
              :href="item.url"
              :title="item.title"
            >
              {{ item.title }}
              <span class="type">
                {{ item.type }}
              </span>
            </a>
          </li>
          <li
            v-else-if="results.length === 0"
            class="no-results"
          >
            {{ __('No results') }}
          </li>
        </ul>
      </div>
    </transition>
  </div>
</template>

<script>
import { get } from 'axios'
import ClickOutside from 'vue-click-outside'
import { SyncLoader } from '@saeris/vue-spinners'
import './SearchForm.scss'

export default {
  name: 'SearchForm',
  
  components: {
    SyncLoader,
  },

  directives: {
    ClickOutside,
  },
  
  props: {
  },

  data() {
    return {
      open: false,
      loading: false,
      value: '',
      results: [],
    };
  },

  created() {
    this.state = this.$props.initialState;
  },

  methods: {
    togglePanel: function () {
      this.open = !this.open

      setTimeout(() => {
        if (this.open) this.$refs['search-value'].focus()
      }, 1)
    },

    hide: function () {
      this.open = false
    },

    search: function () {
      this.loading = true

      get(`${wpData.baseApi}/search`, {
        params: {
          search: this.value,
        },
      })
        .then((response) => {
          console.log(response)

          this.results = response.data
          this.loading = false
        })
    },
  },
};
</script>