<template>
  <itf-popover :visible.sync="isVisible" ref="popover" :trigger="trigger" custom-class="nopadding" :placement="placement">
    <template #activator="{ on }">
      <slot name="activator" :on="on"></slot>
    </template>

    <div class="modal-body py-2 px-3 text-center itf-select-popover">
      <div class="d-flex align-items-center justify-content-between">
        <div class="mb-0" v-if="title" v-html="title"></div>

        <itf-button v-if="removable" small secondary @click="onSelectIcon(null)">
          Remove
        </itf-button>
      </div>

      <div class="d-flex py-2">
        <itf-text-field
          class="flex-grow-1 me-2"
          v-model="search"
          placeholder="Filter"
          prepend-icon="search"
          clearable
        />

        <itf-button v-tooltip="$t('random')" @click="onRandom">
          <itf-icon name="shuffle" />
        </itf-button>
      </div>

      <div v-if="isVisible" class="itf-select-popover__scroll text-start">
        <template v-if="!search && recentIcons.length">
          <div class="py-1 text-muted">Recent</div>
          <div class="d-flex align-items-start flex-wrap flex-grow-0">
            <itf-button v-for="icon of recentIcons" :key="icon" icon v-tooltip="icon" @click="onSelectIcon(icon)">
              <itf-mdi-icon :name="icon" />
            </itf-button>
          </div>

          <div class="py-1 text-muted">Icons</div>
        </template>
        <div class="d-flex align-items-start flex-wrap flex-grow-0">
          <itf-button v-for="icon of iconsList" :key="icon" icon v-tooltip="icon" @click="onSelectIcon(icon)">
            <itf-mdi-icon>{{ icon }}</itf-mdi-icon>
          </itf-button>
        </div>
        <div v-if="!iconsList.length" class="text-muted pt-1">
          No results
        </div>
      </div>
      <slot>
      </slot>
    </div>
  </itf-popover>
</template>
<style lang="scss">
  .itf-select-popover {
    width: 280px;
    min-width: 180px;
    max-width: calc(100vw - 24px);
    height: 356px;
    max-height: 70vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    &__scroll {
      overflow: hidden auto;
      flex-grow: 1;
    }
  }
</style>
<script>
import { Vue, Component, Model, Prop, PropSync } from 'vue-property-decorator';
import itfPopover from './Popover';
import itfIcon from '../icon/Icon';
import itfMdiIcon from '../icon/MdiIcon';
import iconsList from '../icon/icons';
import itfButton from '../button/Button';
import itfTextField from '../text-field/TextField.vue';
import tooltip from '../../directives/tooltip';

const RECENT_ITEMS_KEY = 'itfSelectPopoverRecent';

export default @Component({
  name: 'itfIconPopover',
  directives: {
    tooltip
  },
  components: {
    itfIcon,
    itfMdiIcon,
    itfPopover,
    itfButton,
    itfTextField
  },
})
class itfIconPopover extends Vue {
  @Model('input') value;
  @Prop({ type: String, default: '' }) title;
  @Prop({ type: Boolean, default: '' }) removable;
  @Prop({ type: String, default: 'bottom', validator: (value) => ['bottom', 'left', 'right', 'top'].includes(value) }) placement;
  @Prop({ type: String, default: 'click', validator: (value) => ['click', 'focus', 'hover', 'manual'].includes(value) }) trigger;

  isVisible = false;
  search = '';
  icons = [];
  recentIcons = [];

  async created() {
    this.recentIcons = this.getRecentIcons();
    this.icons = await import('@mdi/js');
  }

  get iconsList() {
    // from cames case
    return Object.keys(this.icons).map(key => key.replace(/([A-Z])/g, '-$1').toLowerCase()).filter((icon) => icon.includes(this.search.toLowerCase()));
  }

  onSelectIcon(icon) {
    this.search = '';
    this.$emit('input', icon);
    this.$refs.popover.hide();

    if (icon) {
      const icons = this.getRecentIcons();
      icons.unshift(icon);
      this.recentIcons = [...new Set(icons.slice(0, 14))];
      localStorage.setItem(RECENT_ITEMS_KEY, JSON.stringify(this.recentIcons));
    }
  }

  getRecentIcons() {
    return localStorage.getItem(RECENT_ITEMS_KEY) ? JSON.parse(localStorage.getItem(RECENT_ITEMS_KEY)) : [];
  }

  onRandom() {
    const keys = Object.keys(iconsList);
    const icon = keys[Math.floor(Math.random() * keys.length)];
    this.onSelectIcon(icon);
  }
}
</script>
