<template>
  <div :class="`${$classPrefix}-tabs-con`">
    <nav :class="`${$classPrefix}-tabs`">
      <div
        v-for="(tab, index) in tabs"
        :key="index"
        :class="[
          `${$classPrefix}-tab--outer`,
        ]"
      >
        <div
          :class="[
            `${$classPrefix}-tab`,
            size ? `${size}` : null,
            {
              'active': activeTab === index,
              'disabled': tab.disabled,
              [`${$classPrefix}-tab--pane`]: pane
            }
          ]"
          @click="changeTab(index)"
        >
          <irbis-icon v-if="tab.icon" :name="tab.icon" />
          <span>{{ tab.label }}</span>
        </div>
        <irbis-button v-if="tab.closeable" subtle @click="closeTab(tab)">
          <irbis-icon name="x" />
        </irbis-button>
      </div>
      <div :class="`${$classPrefix}-tabs-underline`"></div>
    </nav>
    <section>
      <slot activeTab="activeTab" />
    </section>
  </div>
</template>

<script>
// TODO: Khosoo modified styles
// TODO: Tabs have custom values instead of index numbers
export default {
  name: "IrbisTabs",

  props: {
    value: {},
    size: String,
    pane: {
      default: false,
      type: Boolean
    }
  },

  data() {
    return {
      _isTabs: true,
      tabs: [],
      activeTab: this.value || 0
    };
  },

  watch: {
    tabs() {
      if (this.activeTab < this.tabs.length) {
        this.tabs[this.activeTab].isActive = true;
      }
    }
  },

  methods: {
    tabClick(index) {
      this.$emit("input", index);
      this.changeTab(index);
    },

    changeTab(newIndex) {
      if (this.activeTab === newIndex) return;

      this.tabs[this.activeTab].hide();
      this.tabs[newIndex].show();
      this.activeTab = newIndex;
    },

    closeTab(tab) {
      let currentIndex = this.tabs.indexOf(tab);
      let newIndex =
        currentIndex + 1 == this.tabs.length ? currentIndex - 1 : currentIndex;
      this.tabs[currentIndex].hide();
      this.tabs.splice(currentIndex, 1);
      this.tabs[newIndex].show();
      this.activeTab = newIndex;
    }
  }
};
</script>