<template>
  <div
    v-if="keepTabsAlive || active"
    v-show="active"
    :id="`pane-${paneName}`"
    :aria-hidden="!active"
    :aria-labelledby="`tab-${paneName}`"
    class="mm-tab-pane"
    role="tabpanel">
    <slot></slot>
  </div>
</template>

<script>
import isMatch from "lodash/isMatch"

export default {
  name: "mm-tab",
  props: {
    label: String,
    name: String,
    closable: Boolean,
    disabled: Boolean,
    route: [Object, String],
  },
  data() {
    return {
      index: null,
      isMounted: false,
    }
  },
  computed: {
    isClosable() {
      return this.closable || this.$parent.closable
    },
    active() {
      return this.$parent.currentName === (this.name || this.index)
    },
    paneName() {
      return this.name || this.index
    },
    keepTabsAlive() {
      return this.$parent.keepTabsAlive
    },
    paneResolvedPath() {
      return this.$router && this.$router.resolve(this.route || this.paneName).resolved
    },
  },
  watch: {
    $route() {
      if (this.isMounted) {
        this.syncCurrentName()
      }
    },
  },
  updated() {
    this.$parent.$emit("tab-nav-update")
  },
  mounted() {
    const { addPanes } = this.$parent
    addPanes(this)
    this.isMounted = true
    this.syncCurrentName()
  },
  destroyed() {
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el)
    }
    this.$parent.removePanes(this)
  },
  methods: {
    syncCurrentName() {
      const { router, query } = this.$parent
      if (!this.disabled) {
        router ? this.handleRouter() : query && this.handleQuery()
      }
    },
    handleRouter() {
      const { paneResolvedPath, $route } = this
      if (paneResolvedPath.path === $route.path) {
        if (isMatch($route.query, paneResolvedPath.query)) {
          this.parentSetCurrentName()
        }
      }
    },
    handleQuery() {
      const { $parent, paneName, $route } = this
      const { query, queryKey } = $parent
      if (query && $route.query[queryKey] === paneName) {
        this.parentSetCurrentName()
      }
    },
    parentSetCurrentName() {
      this.$parent.setCurrentName(this.paneName)
    },
  },
}
</script>
