<template>
  <ui-select
    class="user-select"
    :options="formattedUsers"
    :value="usernameFilter.name"
    :loading="isLoading"
    disable-filter
    floating-label
    label="User"
    has-search
    search-placeholder="Select user"
    @query-change="onQueryChange"
    @select="handleUsernameSelection"
  >
    <template
      slot="option"
      slot-scope="{option = {}}"
    >
      <div class="option-item">
        <span :class="`option-text ${option.class}`">
          {{ option.label }}
        </span>
      </div>
    </template>
  </ui-select>
</template>
<script>

import _debounce from 'lodash/debounce';
import { fetchUsers } from 'Api';
import { ALL_USERS, DEBOUNCE_TIME_1K } from 'Config/constants';
import { handleUsersRequest } from 'Helpers/api';

const { UiSelect } = window.kiln.utils.components;

export default {
  components: {
    UiSelect
  },
  props: {
    usernameFilter: {
      type: Object,
      default: () => ({})
    },
    users: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      options: [],
      isLoading: false,
      defaultOriginalList: []
    };
  },
  computed: {
    formattedUsers() {
      return this.options.map(user => ({
        label: user.name,
        class: 'option-value',
        value: user.username
      }));
    }
  },
  watch: {
    users() {
      this.defaultOriginalList = this.users;
      this.options = this.users;
    }
  },
  methods: {
    // eslint-disable-next-line func-names
    getUsers: _debounce(function (query) {
      fetchUsers(query)
        .then((data) => {
          this.options = handleUsersRequest(data, false);
          this.isLoading = false;
        });
    }, DEBOUNCE_TIME_1K),
    onQueryChange(query) {
      this.isLoading = true;
      if (query.length) return this.getUsers(query);

      this.options = this.defaultOriginalList;
      this.isLoading = false;
    },
    /**
     * Handles username selection logic
     * @param {Object} e Event object from action
     */
    handleUsernameSelection(e) {
      const index = this.options.findIndex(({ username }) => e.value === username);

      let usernameFilter = this.options[index];

      if (usernameFilter.username === ALL_USERS) {
        this.$emit('handleAllUsers');
        usernameFilter = { username: '', name: '' };
      }

      this.$emit('setUsernameFilter', usernameFilter);
      this.$emit('setOffset'); // move to first page and refresh
    }
  }
};
</script>
<style lang="scss" scoped>
  .user-select.ui-select /deep/ .ui-select__display {
    line-height: 1.4;
  }
</style>
