<script lang="ts">
	import { authStore } from '$lib/stores/auth.svelte';
	import { SvelteDate } from 'svelte/reactivity';
	import { toast } from 'svelte-sonner';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Badge } from '$lib/components/ui/badge';
	import { Skeleton } from '$lib/components/ui/skeleton';

	interface Props {
		openBookingModal: (bookingId: string) => void;
		openEditBookingModal: (bookingId: string, nextAppointmentStart?: string | null) => void;
		openUserModal: (userId: string) => void;
	}

	let { openBookingModal, openEditBookingModal, openUserModal }: Props = $props();

	type Booking = {
		id: string;
		start_time: string;
		status: string;
		notes?: string;
		user?: {
			id: string;
			full_name: string;
			phone?: string;
			profile_pic_url?: string;
		};
		services: Array<{
			service_name?: string;
			service_description?: string;
			price?: number;
			duration_minutes?: number;
		}>;
		duration_minutes: number;
		total_amount: number;
	};

	let currentAppointment = $state<Booking | null>(null);
	let nextAppointment = $state<Booking | null>(null);
	let closingTime = $state<string | null>(null); // "HH:MM" format
	let freeTimeAfter = $state(0); // minutes of free time after current/next appointment
	let freeTimeCapped = $state(false); // true if free time extends to/past closing
	let loading = $state(true);
	let timeRemaining = $state(0); // minutes remaining in current appointment
	let isInProgress = $state(false);

	// Calculate time remaining and free time
	let interval: ReturnType<typeof setInterval> | null = null;

	function calculateTimes() {
		const now = new SvelteDate();

		if (currentAppointment) {
			isInProgress = currentAppointment.status === 'in_progress';
			const startTime = new SvelteDate(currentAppointment.start_time);

			const endTime = new SvelteDate(
				startTime.getTime() + currentAppointment.duration_minutes * 60 * 1000
			);

			if (isInProgress) {
				if (now.getTime() < startTime.getTime()) {
					const timeUntilMs = startTime.getTime() - now.getTime();
					timeRemaining = Math.max(0, Math.floor(timeUntilMs / 60000));
				} else {
					const remainingMs = endTime.getTime() - now.getTime();
					timeRemaining = Math.max(0, Math.floor(remainingMs / 60000));
				}
			} else {
				const timeUntilMs = startTime.getTime() - now.getTime();
				timeRemaining = Math.max(0, Math.floor(timeUntilMs / 60000));
			}

			// Calculate free time after this appointment
			let rawFreeMinutes = 0;
			if (nextAppointment) {
				const nextStart = new SvelteDate(nextAppointment.start_time);
				const gapMs = nextStart.getTime() - endTime.getTime();
				rawFreeMinutes = Math.max(0, Math.floor(gapMs / 60000));
			}

			// Cap at closing time
			if (closingTime) {
				const [ch, cm] = closingTime.split(':').map(Number);
				const today = new SvelteDate();
				const closing = new SvelteDate(today.getFullYear(), today.getMonth() + 1, today.getDate(), ch, cm, 0);
				const minutesToClosing = Math.max(0, Math.floor((closing.getTime() - endTime.getTime()) / 60000));

				if (!nextAppointment) {
					// No next appointment — show time until closing
					freeTimeAfter = minutesToClosing;
					freeTimeCapped = true;
				} else if (rawFreeMinutes > minutesToClosing) {
					// Next appointment is after closing — cap at closing
					freeTimeAfter = minutesToClosing;
					freeTimeCapped = true;
				} else {
					freeTimeAfter = rawFreeMinutes;
					freeTimeCapped = false;
				}
			} else {
				freeTimeAfter = nextAppointment ? rawFreeMinutes : 0;
				freeTimeCapped = false;
			}
		}
	}

	async function fetchCurrentAndNext() {
		loading = true;
		try {
			const response = await fetch('/api/admin/today/current-next', {
				method: 'GET',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${authStore.currentToken}`
				}
			});

			if (response.ok) {
				const data = await response.json();
				currentAppointment = data.current || null;
				nextAppointment = data.next || null;
				closingTime = data.closing_time || null;
				calculateTimes();
			} else {
				toast.error('Failed to load current appointment');
			}
		} catch (err) {
			console.error('Error fetching current appointment:', err);
			toast.error('Network error loading appointment');
		} finally {
			loading = false;
		}
	}

	// Start interval for real-time countdown
	$effect(() => {
		fetchCurrentAndNext();

		interval = setInterval(() => {
			calculateTimes();
		}, 15000); // Update every 15 seconds

		return () => {
			if (interval) clearInterval(interval);
		};
	});

	// WIP Demo actions
	function handleBegin() {
		toast.info('Begin appointment - Coming soon');
	}

	function handleEdit() {
		if (currentAppointment) {
			openEditBookingModal(currentAppointment.id, nextAppointment?.start_time ?? null);
		}
	}

	function handleExtend() {
		toast.info('Extend appointment - Coming soon');
	}

	function handleTakePayment() {
		toast.info('Take payment - Coming soon');
	}

	function handleCancel() {
		toast.info('Cancel appointment - Coming soon');
	}

	const activeAppointment = $derived(currentAppointment || nextAppointment);
</script>

<Card.Root class="border-2 border-blue-200 bg-blue-50">
	<Card.Header>
		<div class="flex items-start justify-between">
			<div>
				<Card.Title class="text-2xl">
					{isInProgress ? 'Current Appointment' : 'Next Appointment'}
				</Card.Title>
				{#if activeAppointment}
					<Card.Description class="text-base">
						{new SvelteDate(activeAppointment.start_time).toLocaleTimeString('en-US', {
							hour: 'numeric',
							minute: '2-digit',
							hour12: true
						})}
						-
						{new SvelteDate(
							new SvelteDate(activeAppointment.start_time).getTime() +
								activeAppointment.duration_minutes * 60 * 1000
						).toLocaleTimeString('en-US', {
							hour: 'numeric',
							minute: '2-digit',
							hour12: true
						})}
					</Card.Description>
				{/if}
			</div>

			{#if activeAppointment}
				{#if isInProgress}
					<div class="flex flex-col gap-2 items-end">
						<Badge class="bg-blue-100 px-3 py-1 text-sm text-blue-800">
							<span class="relative mr-2 flex h-2 w-2">
								<span
									class="absolute inline-flex h-full w-full animate-ping rounded-full bg-blue-400 opacity-75"
								></span>
								<span class="relative inline-flex h-2 w-2 rounded-full bg-blue-600"></span>
							</span>
							In Progress • {timeRemaining} min remaining
						</Badge>
						{#if timeRemaining > 29}
							{#if freeTimeCapped && freeTimeAfter === 0}
								<Badge class="bg-blue-100 px-3 py-1 text-sm text-blue-800">
									closing after
								</Badge>
							{:else if freeTimeAfter > 0}
								<Badge class="bg-blue-100 px-3 py-1 text-sm text-blue-800">
									{freeTimeAfter} min free afterwards{#if freeTimeCapped} (closing after){/if}
								</Badge>
							{/if}
						{/if}
					</div>
				{:else}
					<Badge class="bg-amber-100 px-3 py-1 text-sm text-amber-800">
						Starts in {timeRemaining} min
					</Badge>
				{/if}
			{/if}
		</div>
	</Card.Header>

	{#if loading}
		<Card.Content class="space-y-4">
			<div class="flex gap-4">
				<Skeleton class="h-20 w-20 rounded-full" />
				<div class="flex-1 space-y-2">
					<Skeleton class="h-6 w-48" />
					<Skeleton class="h-4 w-32" />
					<Skeleton class="h-4 w-40" />
				</div>
			</div>
			<Skeleton class="h-32 w-full" />
		</Card.Content>
	{:else if !activeAppointment}
		<Card.Content>
			<div class="py-12 text-center">
				<svg
					xmlns="http://www.w3.org/2000/svg"
					class="mx-auto mb-4 h-16 w-16 text-gray-300"
					fill="none"
					viewBox="0 0 24 24"
					stroke="currentColor"
					stroke-width="1.5"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
					/>
				</svg>
				<p class="text-lg font-medium text-gray-600">No appointments right now</p>
				<p class="text-sm text-gray-500">Enjoy the break or check tomorrow's schedule</p>
			</div>
		</Card.Content>
	{:else}
		<Card.Content>
			<div class="grid gap-6 md:grid-cols-3">
				<!-- Customer Info -->
				<div class="flex items-center gap-4">
					{#if activeAppointment.user?.profile_pic_url}
						<img
							src={activeAppointment.user.profile_pic_url}
							alt={activeAppointment.user.full_name}
							class="h-20 w-20 rounded-full object-cover ring-4 ring-blue-200"
						/>
					{:else}
						{@const initials = activeAppointment.user?.full_name?.split(' ').map(n => n[0]).join('') || '?'}
						<div
							class="flex h-20 w-20 items-center justify-center rounded-full bg-gray-200 text-2xl font-bold text-gray-600 ring-4 ring-blue-200"
						>
							{initials}
						</div>
					{/if}
					<div>
						<div class="text-lg font-semibold">{activeAppointment.user?.full_name || 'Guest'}</div>
						<div class="text-sm text-gray-600">{activeAppointment.user?.phone || '—'}</div>
						{#if activeAppointment.user}
							<button
								type="button"
								class="mt-1 text-xs text-blue-600 hover:underline"
								onclick={() => openUserModal(activeAppointment.user!.id)}
							>
								View customer details →
							</button>
						{/if}
					</div>
				</div>

				<!-- Services List -->
				<div>
					<div class="mb-2 text-sm font-semibold text-gray-700">Services</div>
					<div class="space-y-2">
						{#each activeAppointment.services as service, index (index)}
							<div class="rounded-md border border-gray-200 bg-white p-2 text-sm">
								<div class="font-medium">{service.service_name || 'Unknown Service'}</div>
								{#if service.service_description}
									<div class="text-xs text-gray-600">{service.service_description}</div>
								{/if}
								<div class="mt-1 flex items-center justify-between text-xs text-gray-500">
									<span>{service.duration_minutes} mins</span>
								</div>
							</div>
						{/each}
					</div>
				</div>

				<!-- Notes & Actions -->
				<div class="space-y-3">
					{#if activeAppointment.notes}
						<div class="rounded-md border border-amber-200 bg-amber-50 p-3">
							<div class="mb-1 flex items-center gap-2 text-xs font-semibold text-amber-800">
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-4 w-4"
									viewBox="0 0 20 20"
									fill="currentColor"
								>
									<path
										fill-rule="evenodd"
										d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
										clip-rule="evenodd"
									/>
								</svg>
								Notes
							</div>
							<div class="text-sm text-amber-900">{activeAppointment.notes}</div>
						</div>
					{/if}
					<div class="grid grid-cols-2 gap-2">
						{#if !isInProgress}
							<Button size="sm" onclick={handleBegin} class="col-span-2">
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="mr-2 h-4 w-4"
									viewBox="0 0 20 20"
									fill="currentColor"
								>
									<path
										fill-rule="evenodd"
										d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z"
										clip-rule="evenodd"
									/>
								</svg>
								Begin
							</Button>
						{/if}
						<Button size="sm" variant="outline" onclick={handleEdit}>
							<svg
								xmlns="http://www.w3.org/2000/svg"
								class="mr-2 h-4 w-4"
								viewBox="0 0 20 20"
								fill="currentColor"
							>
								<path
									d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"
								/>
							</svg>
							Edit
						</Button>
						{#if isInProgress}
							<Button size="sm" variant="outline" onclick={handleExtend}>
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="mr-2 h-4 w-4"
									viewBox="0 0 20 20"
									fill="currentColor"
								>
									<path
										fill-rule="evenodd"
										d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
										clip-rule="evenodd"
									/>
								</svg>
								Extend
							</Button>
						{/if}
						<Button size="sm" variant="destructive" onclick={handleCancel}>
							<svg
								xmlns="http://www.w3.org/2000/svg"
								class="mr-2 h-4 w-4"
								viewBox="0 0 20 20"
								fill="currentColor"
							>
								<path
									fill-rule="evenodd"
									d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
									clip-rule="evenodd"
								/>
							</svg>
							Cancel
						</Button>
						<Button size="sm" onclick={handleTakePayment} class="col-span-2 bg-green-600 hover:bg-green-700">
							<svg
								xmlns="http://www.w3.org/2000/svg"
								class="mr-2 h-4 w-4"
								viewBox="0 0 20 20"
								fill="currentColor"
							>
								<path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4z" />
								<path
									fill-rule="evenodd"
									d="M18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z"
									clip-rule="evenodd"
								/>
							</svg>
							Payment
						</Button>
					</div>
				</div>
			</div>
		</Card.Content>
	{/if}
</Card.Root>
