<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';
	import ApprovalModal from '$lib/components/admin/ApprovalModal.svelte';

	interface Props {
		openBookingModal?: (bookingId: string) => void;
	}

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

	// Match the backend structure
	type PendingApproval = {
		id: string;
		start_time: string;
		user_id: string;
		user_name: string; // This is a string, not an object
		services: string[]; // Array of service names
		duration_minutes: number;
		created_at: string;
	};

	type PendingBooking = {
		id: string;
		start_time: string;
		notes?: string;
		user?: {
			id: string;
			full_name: string;
			email?: string;
			phone?: string;
		};
		services: Array<{
			service_id: string;
			service_name?: string;
			price?: number;
			duration_minutes?: number;
		}>;
		duration_minutes: number;
		created_at: string;
	};

	let pendingApprovals = $state<PendingApproval[]>([]);
	let visibleApprovals = $derived(pendingApprovals.slice(0, 3));
	let loading = $state(true);
	let showApprovalModal = $state(false);
	let selectedBooking = $state<PendingBooking | null>(null);

	// Helper function to format date nicely
	function formatDateTime(dateTimeString: string): string {
		const date = new SvelteDate(dateTimeString);
		const dateStr = date.toLocaleDateString('en-US', {
			weekday: 'long',
			day: 'numeric',
			month: 'short'
		});
		const timeStr = date.toLocaleTimeString('en-US', {
			hour: 'numeric',
			minute: '2-digit',
			hour12: true
		});
		return `${dateStr} at ${timeStr}`;
	}

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

			if (response.ok) {
				const data = await response.json();
				pendingApprovals = (data.approvals || []).sort(
					(a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
				);
			} else {
				toast.error('Failed to load pending approvals');
			}
		} catch (err) {
			console.error('Error fetching pending approvals:', err);
			toast.error('Network error loading pending approvals');
		} finally {
			loading = false;
		}
	}

	async function openApprovalModal(bookingId: string) {
		try {
			const response = await fetch(`/api/admin/bookings/${bookingId}`, {
				headers: {
					Authorization: `Bearer ${authStore.currentToken}`
				}
			});
			if (!response.ok) throw new Error(await response.text());

			const data = await response.json();
			selectedBooking = data; // now has full services with price/duration
			showApprovalModal = true;
		} catch (err) {
			console.error('Failed to load booking details:', err);
			toast.error('Failed to load booking details');
		}
	}

	$effect(() => {
		fetchPendingApprovals();

		const intervalId = setInterval(() => {
			fetchPendingApprovals();
		}, 60_000);

		return () => {
			clearInterval(intervalId);
		};
	});
</script>

<Card.Root>
	<Card.Header>
		<div class="flex items-start justify-between">
			<div>
				<Card.Title class="flex items-center gap-2">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-5 w-5 text-amber-600"
						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>
					Pending Approvals
				</Card.Title>
				<Card.Description>New bookings awaiting confirmation</Card.Description>
			</div>
			{#if !loading}
				<Badge class="bg-amber-100 text-amber-800 hover:bg-amber-100">
					{pendingApprovals.length}
				</Badge>
			{/if}
		</div>
	</Card.Header>
	<Card.Content>
		{#if loading}
			<div class="space-y-3">
				{#each Array(3) as _, i (i)}
					<div class="rounded-lg border p-3">
						<div class="flex items-start justify-between">
							<div class="flex-1 space-y-2">
								<Skeleton class="h-4 w-32" />
								<Skeleton class="h-3 w-48" />
								<Skeleton class="h-3 w-24" />
							</div>
							<Skeleton class="h-8 w-20" />
						</div>
					</div>
				{/each}
			</div>
		{:else if pendingApprovals.length === 0}
			<div class="py-8 text-center">
				<svg
					xmlns="http://www.w3.org/2000/svg"
					class="mx-auto mb-3 h-12 w-12 text-gray-300"
					fill="none"
					viewBox="0 0 24 24"
					stroke="currentColor"
					stroke-width="1.5"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
					/>
				</svg>
				<p class="text-sm font-medium text-gray-600">All caught up!</p>
				<p class="text-xs text-gray-500">No pending bookings to review</p>
			</div>
		{:else}
			<div class="space-y-3">
				{#each visibleApprovals as approval (approval.id)}
					<div
						class="rounded-lg border border-amber-200 bg-amber-50/30 p-3 transition-all hover:shadow-md"
					>
						<div class="flex items-start justify-between gap-3">
							<div class="flex-1">
								<div class="font-medium">{approval.user_name || 'Guest'}</div>
								<div class="mt-1 text-sm text-gray-600">
									{approval.services.join(', ')}
								</div>
								<div class="mt-1 text-xs text-gray-500">
									<div class="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
										<span>
											{formatDateTime(approval.start_time)}
										</span>
										<span class="hidden sm:inline">•</span>
										<span>
											{approval.duration_minutes} mins
										</span>
									</div>
								</div>
							</div>
							<div class="flex flex-col gap-2">
								<Button
									size="sm"
									onclick={() => openApprovalModal(approval.id)}
									class="bg-emerald-600 hover:bg-emerald-700"
								>
									Approve
								</Button>
								{#if openBookingModal}
									<Button size="sm" variant="outline" onclick={() => openBookingModal(approval.id)}>
										Details
									</Button>
								{/if}
							</div>
						</div>
					</div>
				{/each}
			</div>
		{/if}
	</Card.Content>
</Card.Root>

<!-- Approval Modal -->
{#if selectedBooking && showApprovalModal}
	<ApprovalModal
		bind:open={showApprovalModal}
		booking={selectedBooking}
		onApproved={() => {
			showApprovalModal = false;
			fetchPendingApprovals();
			window.dispatchEvent(new CustomEvent('bookingApproved'));
		}}
	/>
{/if}
