<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { IconChevronLeft, IconChevronRight } from '$lib/components/icons';

	interface Props {
		month: string; // YYYY-MM format
	}

	let { month }: Props = $props();

	// Parse month into Date object
	let currentDate = $derived.by(() => {
		const [year, monthNum] = month.split('-').map(Number);
		return new Date(year, monthNum - 1, 1);
	});

	let displayMonth = $derived(
		currentDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })
	);

	function formatMonth(date: Date): string {
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		return `${year}-${month}`;
	}

	function navigateMonth(direction: -1 | 1) {
		const date = new Date(currentDate);
		date.setMonth(date.getMonth() + direction);
		const newMonth = formatMonth(date);

		// Preserve other URL params while updating month
		const url = new URL($page.url);
		url.searchParams.set('month', newMonth);
		// Reset to first page when changing month
		url.searchParams.delete('page');
		goto(url.toString());
	}

	function goToCurrentMonth() {
		const newMonth = formatMonth(new Date());
		const url = new URL($page.url);
		url.searchParams.set('month', newMonth);
		url.searchParams.delete('page');
		goto(url.toString());
	}

	let isCurrentMonth = $derived(month === formatMonth(new Date()));
</script>

<div class="flex items-center gap-2">
	<button
		type="button"
		onclick={() => navigateMonth(-1)}
		class="rounded-lg p-2 text-theme-secondary transition-colors hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
		aria-label="Previous month"
	>
		<IconChevronLeft class="h-5 w-5" />
	</button>

	<button
		type="button"
		onclick={goToCurrentMonth}
		disabled={isCurrentMonth}
		class="min-w-[160px] rounded-lg px-4 py-2 text-center font-medium text-theme transition-colors hover:bg-black/5 disabled:cursor-default disabled:hover:bg-transparent dark:hover:bg-white/10"
	>
		{displayMonth}
	</button>

	<button
		type="button"
		onclick={() => navigateMonth(1)}
		class="rounded-lg p-2 text-theme-secondary transition-colors hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
		aria-label="Next month"
	>
		<IconChevronRight class="h-5 w-5" />
	</button>
</div>
