<script lang="ts">
	import { goto } from '$app/navigation';
	import { authStore } from '$lib/stores/auth.svelte';
	import { browser } from '$app/environment';
	import { toast } from 'svelte-sonner';
	import { SvelteDate } from 'svelte/reactivity';
	import UserBookingModal from '$lib/components/account/UserBookingModal.svelte';

	import { Button } from '$lib/components/ui/button';
	import * as Card from '$lib/components/ui/card';

	let pageState = $state<'loading' | 'authorized' | 'unauthorized'>('loading');
	let bookings = $state<any[]>([]);
	let loading = $state(false);
	let selectedBookingId = $state<string | null>(null);
	let showBookingModal = $state(false);

	$effect(() => {
		if (!browser) return;

		if (authStore.isLoading) {
			pageState = 'loading';
			return;
		}

		if (!authStore.isAuthenticated) {
			pageState = 'unauthorized';
			goto('/login', { replaceState: true });
			return;
		}

		pageState = 'authorized';
		fetchBookings();
	});

	async function fetchBookings() {
		loading = true;
		try {
			const today = new Date().toISOString().split('T')[0];
			const response = await fetch(`/api/bookings?start_date=${today}&per_page=50&page=1`, {
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${authStore.currentToken}`
				}
			});

			if (!response.ok) {
				toast.error('Failed to load bookings');
				return;
			}

			const data = await response.json();
			const now = new Date();

			bookings = (data.bookings || [])
				.filter((b: any) => {
					const startTime = new Date(b.start_time);
					const endTime = new Date(startTime.getTime() + (b.duration_minutes || 0) * 60000);
					return endTime > now;
				})
				.sort(
					(a: any, b: any) => new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
				);
		} catch (err) {
			console.error('Error fetching bookings:', err);
			toast.error('Network error');
		} finally {
			loading = false;
		}
	}

	function openBooking(id: string) {
		selectedBookingId = id;
		showBookingModal = true;
	}

	const statusColors: Record<string, string> = {
		pending: 'bg-yellow-100 text-yellow-800',
		confirmed: 'bg-green-100 text-green-800',
		in_progress: 'bg-blue-100 text-blue-800',
		completed: 'bg-gray-100 text-gray-800'
	};
</script>

{#if pageState === 'loading'}
	<div class="mx-auto max-w-4xl p-6">
		<div class="animate-pulse space-y-4">
			<div class="h-8 w-48 rounded bg-gray-200"></div>
			<div class="h-64 rounded bg-gray-200"></div>
		</div>
	</div>
{:else if pageState === 'unauthorized'}
	<div class="mx-auto max-w-4xl p-6 text-center">
		<p>Please log in to view your schedule.</p>
	</div>
{:else}
	<div class="mx-auto max-w-4xl p-6">
		<h1 class="mb-6 text-2xl font-bold">My Schedule</h1>

		{#if loading}
			<div class="text-center">Loading...</div>
		{:else if bookings.length === 0}
			<Card.Root>
				<Card.Header>
					<Card.Title>No Upcoming Appointments</Card.Title>
					<Card.Description>You don't have any upcoming appointments.</Card.Description>
				</Card.Header>
				<Card.Content>
					<Button href="/book">Book an Appointment</Button>
				</Card.Content>
			</Card.Root>
		{:else}
			<div class="space-y-4">
				{#each bookings as booking (booking.id)}
					<Card.Root>
						<Card.Header class="flex flex-row items-center justify-between pb-2">
							<div>
								<Card.Title class="text-lg">
									{new SvelteDate(booking.start_time).toLocaleDateString('en-GB', {
										weekday: 'long',
										day: 'numeric',
										month: 'long',
										year: 'numeric'
									})}
								</Card.Title>
								<Card.Description>
									{new SvelteDate(booking.start_time).toLocaleTimeString('en-GB', {
										hour: 'numeric',
										minute: '2-digit'
									})}
									{#if booking.duration_minutes}
										<span class="text-gray-500"> · {booking.duration_minutes} min</span>
									{/if}
								</Card.Description>
							</div>
							<span
								class="rounded-full px-2 py-1 text-xs font-medium {statusColors[booking.status] ||
									'bg-gray-100 text-gray-800'}"
							>
								{booking.status}
							</span>
						</Card.Header>
						<Card.Content>
							<div class="flex items-center justify-between">
								<div>
									{#if booking.services && booking.services.length > 0}
										<p class="font-medium">
											{booking.services.map((s: any) => s.service_name).join(', ')}
										</p>
									{/if}
									{#if booking.total_amount}
										<p class="text-sm text-gray-500">£{booking.total_amount.toFixed(2)}</p>
									{/if}
								</div>
								<div class="flex gap-2">
									<Button size="sm" onclick={() => openBooking(booking.id)}>View Details</Button>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				{/each}
			</div>
		{/if}
	</div>
{/if}

<UserBookingModal bind:open={showBookingModal} bookingId={selectedBookingId || ''} />
