<template>
  <div class="mc-tabs" :class="[typeClass, layoutClass]">
  <template v-if="this.layout!='bottom'">
    <ul class="mc-tab_list" >
      <li v-for="(tab, index) in tabPanes"
          :class="{ 'is-active': isActive(index), 'is-disabled': tab.disabled, }" role="tab">
          <a @click.prevent="handleSelect(index)">
            <i v-if="tab.icon" class="mc-tabs_icon" :class="[`mc-icon-${tab.icon}`]"></i>{{ tab.label }}
          </a>
      </li>
    </ul>
    <div class="mc-tab_content">
      <slot></slot>
    </div>
  </template>
  <template v-else>
    <div class="mc-tab_content">
      <slot></slot>
    </div>
    <ul class="mc-tab_list" >
      <li v-for="(tab, index) in tabPanes"
          :class="{ 'is-active': isActive(index), 'is-disabled': tab.disabled, }" role="tab">
          <a @click.prevent="handleSelect(index)">
            <i v-if="tab.icon" class="mc-tabs_icon" :class="[`mc-icon-${tab.icon}`]"></i>{{ tab.label }}
          </a>
      </li>
    </ul>
  </template>
  </div>
</template>
<script>
export default {
  props: {
    isFullWidth: Boolean,
    layout: {
      type: String,
      default: 'top',
      validator(val) {
        return ['top', 'bottom', 'left', 'right'].indexOf(val) > -1;
      },
    },
    type: {
      type: String,
      default: '',
    },
    activeIndex: {
      type: Number,
      default: 0,
    },
    animation: {
      type: String,
      default: 'fade',
    },
    onlyFade: {
      type: Boolean,
      default: true,
    },
    onTabClick: {
      type: Function,
      default() {},
    },
    transition: {
      type: String,
      default: 'fade',
    },
  },

  data() {
    return {
      tabPanes: [],
      selectedIndex: 0,
      prevSelectedIndex: -1,
    };
  },

  watch: {
    activeIndex(val) {
      this.selectedIndex = val;
    },
  },

  computed: {
    typeClass() {
      return this.type ? `is-${this.type}` : null;
    },
    layoutClass() {
      return this.layout ? `is-${this.layout}` : null;
    },
  },

  methods: {
    isActive(index) {
      return index === this.selectedIndex;
    },

    handleSelect(index) {
      if (this.prevSelectedIndex !== -1) {
        this.tabPanes[this.selectedIndex].deActivated();
      }
      this.prevSelectedIndex = this.selectedIndex;
      this.selectedIndex = index;
      this.tabPanes[index].onActivated(index, this.prevSelectedIndex);
      this.onTabClick(index);
    },
  },

  mounted() {
    this.tabPanes = this.$children.filter(child => child.isTabPane);

    this.handleSelect(this.activeIndex);
  },
};
</script>

