<template>
  <ui-select
    class="form-element"
    :floating-label="floatingLabel"
    disable-filter
    label="Tags"
    multiple
    :help="helpMessage"
    :invalid="isInvalid"
    :placeholder="placeholder"
    :value="selectedTags"
    :options="formattedTags"
    @select="selectTag"
  >
    <template
      slot="option"
      slot-scope="{ option = {} }"
    >
      <div
        class="option-item"
        :class="`${option.class} ${selectedTags.includes(option.value) ? 'is-selected': ''}`"
      >
        <span class="option-text">
          {{ option.label }}
        </span>
        <ui-icon
          v-show="option.class !== 'option-title'"
          :icon="selectedTags.includes(option.value) ? 'check_box' : 'check_box_outline_blank'"
        />
      </div>
    </template>
  </ui-select>
</template>
<script>

/*
 * import * as _localStorage from 'Helpers/localStorage';
 * import { LOCAL_STORAGE_KEYS } from 'Config/constants';
 */
import _get from 'lodash/get';
import { isNotValid } from 'Helpers/validation';

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

function addTagToLocalStorage() {
  /*
   * const onUploadTag = _localStorage.get(LOCAL_STORAGE_KEYS.onUploadTag),
   *  persistentCategories = Object.values(tags)
   *    .reduce((acum, category) => {
   *      if (category.persistent) acum.push(category.name.toLowerCase());
   *      return acum;
   *    }, []),
   *  tagGroup = _class.split(' ').pop();
   *
   * if (!onUploadTag && persistentCategories.includes(tagGroup)) {
   *   _localStorage.set(LOCAL_STORAGE_KEYS.onUploadTag, value);
   * }
   */
}

export default {
  components: {
    UiSelect,
    UiIcon
  },
  props: {
    providedTags: {
      type: Object,
      default: () => ({})
    },
    selectedTags: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: ''
    },
    floatingLabel: {
      type: Boolean,
      default: true
    },
    validation: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    formattedTags() {
      const tags = Object.values(this.providedTags).reduce((accum, item) => {
        const temporal = [...accum];

        temporal.push({
          label: item.name,
          class: 'option-title'
        });

        const items = item.values.map(label => ({
          label,
          class: `option-value ${item.name.toLowerCase()}`,
          value: label
        })) || [];

        return [
          ...temporal,
          ...items
        ];
      }, []);

      return tags;
    },
    isInvalid() {
      const validation = _get(this.validation, 'eval', []),
        isNotValidField = validation
          && validation.some(currentEvaluation => isNotValid(currentEvaluation, this.selectedTags));

      return !!this.validation && isNotValidField;
    },
    helpMessage() {
      return this.isInvalid ? this.validation.message : '';
    }
  },
  methods: {
    /**
     * Handles the select event when a tag is clicked
     * @param {Object} e Event object from action
     */
    selectTag(e) {
      if (e.class === 'option-title') {
        return;
      }

      let tags = this.selectedTags;
      const index = tags.findIndex(item => e.value === item);

      if (tags.includes(e.value)) {
        tags = [
          ...tags.slice(0, index),
          ...tags.slice(index + 1)
        ];
      } else {
        tags.push(e.value);
        addTagToLocalStorage(e, this.providedTags);
      }

      this.$emit('selectTags', tags);
    }
  }
};
</script>
<style lang="scss" scoped>
  @import 'Styles/colors.scss';
  @import 'Styles/helpers.scss';

  .option-item {
    align-items: center;
    display: flex;
    width: 100%;

    &.is-selected {
      background-color: $light-gray--bg;
    }
  }

  .option-text {
    flex: 1
  }

  .option-title {
    cursor: default;
    font-weight: bold;
    text-transform: capitalize;
  }

  .option-title,
  .option-value {
    padding: 0.375rem 0.75rem;
  }

  .ui-select {
    @extend .select-nowrap-style;

    /deep/ .ui-select-option--type-basic {
      padding: 0;
    }
  }

  .ui-icon {
    color: $checkbox-default;
  }

  .ui-icon.check_box,
  .option-item.is-selected {
    color: $cyan-shade;
    font-weight: 500;
  }
</style>
