<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';

	interface StatusCounts {
		scheduled: number;
		inProgress: number;
		completed: number;
		cancelled: number;
	}

	type StatusValue = 'SCHEDULED' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED' | null;

	interface Props {
		counts: StatusCounts;
		currentStatus: StatusValue;
		showCancelled?: boolean;
	}

	let { counts, currentStatus, showCancelled = false }: Props = $props();

	interface Tab {
		label: string;
		value: StatusValue;
		count: number;
		colorClass: string;
		activeColorClass: string;
	}

	let tabs = $derived.by<Tab[]>(() => {
		const baseTabs: Tab[] = [
			{
				label: 'All',
				value: null,
				count:
					counts.scheduled +
					counts.inProgress +
					counts.completed +
					(showCancelled ? counts.cancelled : 0),
				colorClass: 'text-theme-secondary',
				activeColorClass: 'bg-theme text-white'
			},
			{
				label: 'Scheduled',
				value: 'SCHEDULED',
				count: counts.scheduled,
				colorClass: 'text-accent2-600 dark:text-accent2-400',
				activeColorClass: 'bg-accent2-500 text-white'
			},
			{
				label: 'In Progress',
				value: 'IN_PROGRESS',
				count: counts.inProgress,
				colorClass: 'text-accent-600 dark:text-accent-400',
				activeColorClass: 'bg-accent-500 text-white'
			},
			{
				label: 'Completed',
				value: 'COMPLETED',
				count: counts.completed,
				colorClass: 'text-primary-600 dark:text-primary-400',
				activeColorClass: 'bg-primary-500 text-white'
			}
		];

		if (showCancelled) {
			baseTabs.push({
				label: 'Cancelled',
				value: 'CANCELLED',
				count: counts.cancelled,
				colorClass: 'text-red-600 dark:text-red-400',
				activeColorClass: 'bg-red-500 text-white'
			});
		}

		return baseTabs;
	});

	function selectStatus(status: StatusValue) {
		const url = new URL($page.url);
		if (status) {
			url.searchParams.set('status', status);
		} else {
			url.searchParams.delete('status');
		}
		// Reset to first page when changing status
		url.searchParams.delete('page');
		goto(url.toString());
	}
</script>

<div class="flex flex-wrap gap-1 sm:gap-2">
	{#each tabs as tab}
		<button
			type="button"
			onclick={() => selectStatus(tab.value)}
			class="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors
				{currentStatus === tab.value
				? tab.activeColorClass
				: 'hover:bg-black/5 dark:hover:bg-white/10 ' + tab.colorClass}"
		>
			<span>{tab.label}</span>
			<span
				class="rounded-full px-1.5 py-0.5 text-xs
					{currentStatus === tab.value ? 'bg-white/20' : 'bg-black/10 dark:bg-white/10'}"
			>
				{tab.count}
			</span>
		</button>
	{/each}
</div>
