<template>
  <div class="d-lg-none itf-tab-dropdown my-2">
    <itf-select
      :options="getOptions()"
      :reduce="(item) => item.id"
      :get-option-key="(item) => item.id"
      :get-option-label="(item) => item.text"
      :value="value"
      @input="onTabSelect"
    >
      <template #option="{ option }">
        <v-nodes :nodes="[option.node]" />
      </template>
      <template #selected-option="{ option }">
        <v-nodes :nodes="[option.node]" />
      </template>
    </itf-select>
  </div>
</template>
<style lang="scss">
.itf-tab-dropdown {
  .itf-tab a {
    pointer-events: none;
  }
}
</style>
<script>
import {Vue, Component, Prop, Provide, Inject} from 'vue-property-decorator';
import itfSelect from '../select/Select';

export default @Component({
  name: 'itfTabDropdown',
  components: {
    itfSelect,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.nodes
    }
  }
})
class itfTabDropdown extends Vue {
  @Inject({ default: null }) tabsManager;
  @Prop(Array) nodes;

  get value() {
    const option = this.getOptions().find(({ node }) => this.tabsManager.isActive(node));
    return option && option.id;
  }

  getOptions() {
    const opts = this.nodes.map(node => {
      const id = node.componentInstance ? (node.componentInstance.id || node.componentInstance._uid) : '-';
      const text = node.elm ? node.elm.textContent : '';
      return { id, text: text.trim(), node }
    });
    return opts;
  }

  onTabSelect(itemId) {
    const option = this.getOptions().find(({ id }) => itemId === id);
    if (option) {
      if (option.node.componentInstance.to) {
        this.$router.push(option.node.componentInstance.to);
      }
    }
    this.tabsManager.setValue(itemId);
  }
}
</script>
