<template>
  <li class="nav-item">
    <slot>
      <a
        class="nav-link"
        :class="{ active, disabled: tabIsDisabled() }"
        aria-current="page"
        :href="tabHref"
        :disabled="tabIsDisabled()"
        @click="onTabClicked()"
      >
        {{ tabLabel }}
      </a>
    </slot>
  </li>
</template>

<script setup lang="ts">
import { computed, PropType } from 'vue';
import { TabItem } from '@/types/custom-types';
import { useIds } from '@/composables/use-ids';

const { getId } = useIds();

const props = defineProps({
  tabItem: {
    type: Object as PropType<TabItem>,
    required: false,
    default: null,
  },
  tab: {
    type: Number,
    default: -1,
  },
  active: {
    type: Boolean,
    required: false,
    default: false,
  },
  disabled: {
    type: Boolean,
    required: false,
    default: false,
  },
  label: {
    type: String,
    required: false,
    default: '',
  },
  href: {
    type: String,
    required: false,
    default: '',
  },
});
const emit = defineEmits(['tab-selected']);

const tabHref = computed(() => props.tabItem?.href || props.href || '#');
const tabLabel = computed(() => props.tabItem?.label || props.label || '');

const tabIsDisabled = () => {
  if (props.disabled) {
    return true;
  }
  if (!!props.tabItem?.disabled && typeof props.tabItem.disabled === 'function') {
    return props.tabItem.disabled();
  }
  return false;
};

const onTabClicked = () => {
  if (tabIsDisabled()) {
    return;
  }

  const tabItem: TabItem = {} as any;
  tabItem.key = props.tabItem?.key || getId('tab-item');
  tabItem.label = tabLabel.value;
  tabItem.disabled = props.tabItem?.disabled || (() => props.disabled);
  tabItem.href = tabHref.value;
  tabItem.tab = props.tabItem?.tab;
  if (!tabItem.tab && tabItem.tab !== 0) {
    tabItem.tab = props.tab;
  }
  emit('tab-selected', tabItem);
};
</script>

<style lang="scss">
.nav-item {
  .nav-link:not(.disabled) {
    cursor: pointer;
  }
}
</style>
