<template>
	<div role="navigation" :class="tabClass">
		<div class="wcc-nav-tabs-container">
			<ul :class="tabItemClass">
				<li
					v-for="(tab, index) in tabs"
					v-bind:key="index"
					:class="[
						'wcc-nav-tab-item',
						{ active: tab.isActive },
						{ valid: index < activeTabIndex },
					]"
					:index="index"
					v-show="tab.title"
					:data-test-id="`wcc-tab-${tab.dataTestId}`"
				>
					<button
						class="wcc-nav-tab-button"
						:class="{ 'wcc-nav-tab-has-subtitle': hasSubTitle(tab) === true }"
						@click="navigateToTab(index)"
					>
						<span class="wcc-nav-tab-item-title">
							{{ tab.title }}
						</span>
						<span :v-if="hasSubTitle(tab)" class="wcc-nav-tab-sub-title">{{
							tab.subTitle
						}}</span>
						<span v-if="type === 'step' && tab.step" class="wcc-nav-tab-icon">{{
							tab.step
						}}</span>
					</button>
				</li>
			</ul>
		</div>
		<div class="wcc-nav-tab-content-container">
			<slot></slot>
		</div>
	</div>
</template>
<script>
export default {
	name: "NavTabs",
	props: {
		onTabChange: { type: Function },
		type: { type: String, default: "vertical" },
	},
	data() {
		return {
			activeTabIndex: 0,
			actualIndex: 1,
			rawTabs: [],
		};
	},
	created() {
		this.rawTabs = this.$children;
	},
	methods: {
		setActiveTab(stab) {
			this.tabs.forEach((tab) => {
				tab.isActive = tab.title === stab.title;
			});
		},
		navigateToTab(index) {
			this.changeTab(this.activeTabIndex, index);
		},
		changeTab(oldIndex, newIndex) {
			let oldTab = this.tabs[oldIndex];
			let newTab = this.tabs[newIndex];
			if (oldTab) {
				oldTab.isActive = false;
			}
			if (newTab) {
				newTab.isActive = true;
				this.runCallback(newTab);
			}
			this.activeTabIndex = newIndex;
		},
		getActiveTab() {
			let activeTab = false;
			this.tabs.forEach((tab) => {
				if (true === tab.isActive) {
					activeTab = tab;
				}
			});
			return activeTab;
		},
		setDefaultActiveTab() {
			if (this.tabs[0]) {
				this.tabs[0].isActive = true;
			}
		},
		hasSubTitle(tab) {
			return !!tab.subTitle;
		},
		runCallback(tab) {
			if (this.onTabChange) {
				this.onTabChange(tab);
			}
		},
	},
	mounted() {
		this.setDefaultActiveTab();
		this.runCallback(this.getActiveTab());
	},
	computed: {
		tabClass() {
			return {
				"wcc-nav-tab": true,
				"wcc-vertical-tab": this.type === "vertical",
				"wcc-horizontal-tab": this.type === "horizontal",
			};
		},
		tabItemClass() {
			return {
				"wcc-vertical-tabs": this.type === "vertical",
				"wcc-horizontal-tabs": this.type === "horizontal",
				"wcc-step-tabs": this.type === "step",
			};
		},
		tabCount() {
			return this.tabs.length;
		},
		isLastTab() {
			return this.activeTabIndex === this.tabCount - 1;
		},
		tabs() {
			const tabs = this.rawTabs;
			let step = 1;
			tabs.map(function (element) {
				element.title != ""
					? ((element.step = step), (step = step + 1))
					: false;
				return element;
			});
			return tabs;
		},
	},
};
</script>
