<template>
  <div
    v-if="shouldBeRender"
    v-show="isActive"
    ref="test"
    role="tabpanel"
    class="vc-tabs-pane"
  >
    <slot
      v-if="$slots[name]"
      :name="$slots[name]"
      :data="tabData"
    >
      <component :is="$slots[name]" />
    </slot>
    <slot
      v-else
      :data="tabData"
    >
      Tab Pane Content
    </slot>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { VcPaneType } from '@/components/VcTabs/VcTabs.types'

export default defineComponent({
  name: 'VcTabsPane',
  inject: ['tabActiveName', 'registerPane', 'unregisterPane'],
  props: {
    label: {
      type: String,
      default: ''
    },
    name: {
      type: [String, Number],
      required: true
    },
    closable: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    lazy: {
      type: Boolean,
      default: false
    },
    icon: {
      type: String,
      default: ''
    },
    tabData: {
      type: Object,
      default: () => ({})
    },
    index: {
      type: Number,
      default: 0
    },
    navClass: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      paneData: {},
      loaded: false
    }
  },
  computed: {
    activeName () {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const fn = (this as any).tabActiveName
      if (fn === undefined) {
        console.error('Use <VcTabs><VcTabPane></VcTabPane></VcTabs>')
        return
      }
      return fn()
    },
    isActive () {
      return this.name === this.activeName
    },
    shouldBeRender () {
      return !this.lazy || (this.loaded || this.isActive)
    }
  },
  watch: {
    isActive: {
      immediate: true,
      handler (val: boolean) {
        this.loaded = val
      }
    }
  },
  mounted () {
    const paneData = {
      paneName: this.name,
      active: this.isActive,
      icon: this.icon,
      label: this.label,
      props: this.$props,
      slots: this.$slots,
      disabled: this.disabled,
      isClosable: this.closable,
      tabData: this.tabData,
      navClass: this.navClass
    } as VcPaneType
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (this as any).registerPane(paneData)
  },
  unmounted () {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (this as any).unregisterPane(this.name)
  }
})
</script>

<style lang="scss">
  .vc-tab-pane {
    @apply relative overflow-hidden;
  }
</style>
