<script lang="ts">
	import type { CalendarDate } from '@internationalized/date';
	import { Button } from '$lib/components/ui/button';

	const {
		date,
		groupedTimeSlots = [],
		selectedTime = null,
		formattedDate,
		onselect
	}: {
		date: CalendarDate | undefined;
		groupedTimeSlots?: Array<{
			type: 'available' | 'unavailable';
			startTime: string;
			endTime: string;
			isGrouped?: boolean;
		}>;
		selectedTime?: string | null;
		formattedDate?: string;
		onselect?: (time: string) => void;
	} = $props();

	function formatTime(time: string): string {
		const parts = time.split(':').map(Number);
		const hours = parts[0];
		const minutes = parts.length > 1 ? parts[1] : 0;

		if (hours === 12 && minutes === 0) {
			return 'Noon';
		} else if (hours === 0 && minutes === 0) {
			return 'Midnight';
		}

		const period = hours >= 12 ? 'PM' : 'AM';
		const displayHours = hours % 12 || 12;
		return `${displayHours}:${minutes.toString().padStart(2, '0')} ${period}`;
	}
</script>

<div
	class="inset-y-0 right-0 no-scrollbar flex max-h-40 w-full scroll-pb-6 flex-col gap-4 overflow-y-auto border-t p-6 md:absolute md:max-h-none md:w-56 md:border-t-0 md:border-l"
>
	{#if groupedTimeSlots.length > 0}
		{#if formattedDate}
			<div class="grid justify-center gap-2">{formattedDate}</div>
		{/if}

		<div class="grid gap-2">
			{#each groupedTimeSlots as slot (slot.type + '-' + slot.startTime + '-' + slot.endTime)}
				{#if slot.type === 'available'}
					<!-- Available slot -->
					<Button
						variant="outline"
						onclick={() => {
							if (onselect) {
								onselect(slot.startTime);
							}
						}}
						class={`w-full hover:bg-fuchsia-50 ${slot.startTime === selectedTime ? 'bg-fuchsia-100' : ''}`}
					>
						{formatTime(slot.startTime)}
						<span class="text-gray-500">- {formatTime(slot.endTime)}</span>
					</Button>
				{:else}
					<!-- Unavailable slot (already booked) -->
					<Button
						variant="outline"
						class="w-full cursor-not-allowed opacity-50 hover:bg-gray-100"
						disabled
					>
						{formatTime(slot.startTime)}
						<span class="text-gray-500">- {formatTime(slot.endTime)}</span>
					</Button>
				{/if}
			{/each}
		</div>
	{:else if !date}
		<p class="text-center text-sm text-gray-500">Select a date first</p>
	{:else}
		<p class="text-center text-sm text-gray-500">No available slots</p>
	{/if}
</div>
