<script lang="ts">
	import { goto } from '$app/navigation';
	import { navigating, page } from '$app/state';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

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

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

	let isPickerOpen = $state(false);
	let isLoading = $derived(navigating.to !== null);

	// Parse current value
	let currentYear = $derived(parseInt(value.split('-')[0]));
	let currentMonth = $derived(parseInt(value.split('-')[1]));

	// Format for display
	let displayText = $derived(() => {
		const date = new Date(currentYear, currentMonth - 1);
		return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
	});

	// Generate picker options (12 months: 6 before, current, 5 after)
	let pickerMonths = $derived(() => {
		const months: { value: string; label: string }[] = [];
		const today = new Date();

		for (let i = -6; i <= 5; i++) {
			const date = new Date(today.getFullYear(), today.getMonth() + i, 1);
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			months.push({
				value: `${year}-${month}`,
				label: date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' })
			});
		}

		return months;
	});

	function navigateMonth(delta: number) {
		const date = new Date(currentYear, currentMonth - 1 + delta, 1);
		const year = date.getFullYear();
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		updateMonth(`${year}-${month}`);
	}

	function updateMonth(newMonth: string) {
		const url = new URL(page.url);
		url.searchParams.set('month', newMonth);
		goto(url.toString(), { replaceState: true, noScroll: true });
		isPickerOpen = false;
	}

	function handleKeydown(event: KeyboardEvent) {
		if (event.key === 'Escape') {
			isPickerOpen = false;
		}
	}
</script>

<svelte:window onkeydown={handleKeydown} />

<div class="relative inline-flex items-center gap-1">
	<!-- Previous Month Button -->
	<button
		type="button"
		onclick={() => navigateMonth(-1)}
		class="rounded-lg p-2 text-theme-secondary transition-colors hover:bg-black/5 active:bg-black/10 disabled:opacity-50 dark:hover:bg-white/10 dark:active:bg-white/15"
		aria-label="Previous month"
		disabled={isLoading}
	>
		<svg
			class="h-5 w-5"
			style="fill: none"
			viewBox="0 0 24 24"
			stroke="currentColor"
			stroke-width="2"
		>
			<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
		</svg>
	</button>

	<!-- Month Display / Picker Toggle -->
	<button
		type="button"
		onclick={() => (isPickerOpen = !isPickerOpen)}
		class="min-w-[160px] rounded-lg px-4 py-2 font-medium text-theme transition-colors hover:bg-black/5 active:bg-black/10 dark:hover:bg-white/10 dark:active:bg-white/15"
		aria-expanded={isPickerOpen}
		aria-haspopup="true"
		disabled={isLoading}
	>
		{#if isLoading}
			<span class="flex items-center justify-center gap-2">
				<IconSpinner class="h-4 w-4" />
				<span>Loading...</span>
			</span>
		{:else}
			{displayText()}
		{/if}
	</button>

	<!-- Next Month Button -->
	<button
		type="button"
		onclick={() => navigateMonth(1)}
		class="rounded-lg p-2 text-theme-secondary transition-colors hover:bg-black/5 active:bg-black/10 disabled:opacity-50 dark:hover:bg-white/10 dark:active:bg-white/15"
		aria-label="Next month"
		disabled={isLoading}
	>
		<svg
			class="h-5 w-5"
			style="fill: none"
			viewBox="0 0 24 24"
			stroke="currentColor"
			stroke-width="2"
		>
			<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
		</svg>
	</button>

	<!-- Dropdown Picker -->
	{#if isPickerOpen}
		<div
			class="absolute top-full left-1/2 z-50 mt-2 min-w-[280px] -translate-x-1/2 rounded-lg border-theme bg-theme-card p-2 shadow-theme-lg"
			role="listbox"
		>
			<div class="grid grid-cols-3 gap-1">
				{#each pickerMonths() as month (month.value)}
					<button
						type="button"
						onclick={() => updateMonth(month.value)}
						class="rounded-md px-3 py-2 text-sm transition-colors
							{month.value === value
							? 'bg-primary-600 text-white'
							: 'text-theme hover:bg-black/5 dark:hover:bg-white/10'}"
						role="option"
						aria-selected={month.value === value}
					>
						{month.label}
					</button>
				{/each}
			</div>
		</div>
	{/if}
</div>

<!-- Click outside to close -->
{#if isPickerOpen}
	<button
		type="button"
		class="fixed inset-0 z-40"
		onclick={() => (isPickerOpen = false)}
		aria-label="Close month picker"
	></button>
{/if}
