<template>
  <UiTabs
    :title="title"
    :tabs="computedTabs"
    :selected-tab-id="selectedTabId"
    @click="onClick"
  >
    <template v-if="needRouterEngine" #router="{ tab }">
      <router-link
        class="tab"
        :to="getTabTarget(tab)"
        :class="{
          active: isTabSelected(tab, selectedTabId),
          error: tab.error,
          disabled: tab.disabled,
        }"
        @click="onClick(tab)"
        >{{ tab.name }}</router-link
      >
    </template>
  </UiTabs>
</template>

<script setup lang="ts">
import { Tab } from '@/models/tab.model';
import UiTabs from './UiTabs.vue';
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
  getTabId,
  isTabSelected,
  isTabSelectedByRoute,
} from '@/helpers/tab.helper';

const { currentRoute } = useRouter();

const props = defineProps<{
  title: string;
  tabs: Tab[];
  initialTabId?: string;
}>();

const selectedTabId = ref<string | null>(null);

const getTabTarget = (tab: Tab) => {
  return tab.routePath ? { path: tab.routePath } : { name: tab.routeName };
};

const $emits = defineEmits<{
  (e: 'click', tab: Tab): void;
}>();

const needRouterEngine = computed(() => {
  return (
    !!props.tabs &&
    !!props.tabs[0] &&
    !!(props.tabs[0].routePath || props.tabs[0].routeName)
  );
});

const onClick = (tab: Tab) => {
  selectedTabId.value = getTabId(tab);
  $emits('click', tab);
};

const computedTabs = computed(() => {
  return props.tabs.map((tab) => {
    return { ...tab, id: getTabId(tab) }; // retro compatibility for id
  });
});

const computedInitialTabId = () => {
  if (needRouterEngine.value) {
    const selectedTab =
      props.tabs.find((t) => isTabSelectedByRoute(t, currentRoute.value)) ||
      null;
    selectedTabId.value = selectedTab ? getTabId(selectedTab) : null;
  } else if (props.initialTabId) {
    selectedTabId.value = props.initialTabId;
  } else {
    selectedTabId.value = null;
  }
};

onMounted(() => {
  computedInitialTabId();
});

watch(
  () => props.initialTabId,
  () => {
    computedInitialTabId();
  },
);
</script>
