<script lang="ts">
	import { goto } from '$app/navigation';
	import { authStore } from '$lib/stores/auth.svelte';
	import { browser } from '$app/environment';

	// shadcn-svelte components
	import { Button } from '$lib/components/ui/button';
	import * as Card from '$lib/components/ui/card';
	import { Skeleton } from '$lib/components/ui/skeleton';
	import { Separator } from '$lib/components/ui/separator';

	// =============== Auth & Permissions ===============
	let pageState = $state<'loading' | 'authorized' | 'unauthorized'>('loading');

	// Check permissions immediately and on auth changes
	$effect(() => {
		if (!browser) return;

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

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

		if (authStore.currentUser?.role !== 'admin') {
			pageState = 'unauthorized';
			goto('/', { replaceState: true });
			return;
		}

		pageState = 'authorized';
	});

	// =============== Pending Bookings State ===============
	type Booking = {
		id: string;
		start_time: string;
		status:
			| 'pending'
			| 'confirmed'
			| 'in_progress'
			| 'completed'
			| 'client_cancelled'
			| 'we_cancelled'
			| 're-schedule'
			| 'no_show';
		notes?: string;
		created_at: string;
		updated_at: string;
		user?: {
			id: string;
			full_name: string;
			email?: string;
			phone?: string;
		};
		services: Array<{
			service_name?: string;
			price?: number;
			duration_minutes?: number;
		}>;
		total_amount: number;
		amount_paid: number;
		amount_due: number;
		duration_minutes: number;
	};

	let pendingBookings = $state<Booking[]>([]);
	let loadingBookings = $state(true);

	// Fetch pending bookings
	async function fetchPendingBookings() {
		if (pageState !== 'authorized') return;

		loadingBookings = true;
		try {
			const response = await fetch('/api/admin/bookings?status=pending', {
				method: 'GET',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${authStore.currentToken}`
				}
			});

			if (response.ok) {
				const data = await response.json();

				if (data.bookings && data.bookings.length > 0) {
					pendingBookings = data.bookings
						.filter((b) => b.status === 'pending')
						.map((b) => ({
							id: b.id,
							start_time: b.start_time,
							status: b.status,
							notes: b.notes,
							created_at: b.created_at,
							updated_at: b.updated_at,
							user: b.user
								? {
										id: b.user.id,
										full_name: b.user.full_name,
										email: b.user.email,
										phone: b.user.phone
									}
								: undefined,
							services: b.services || [],
							total_amount: b.total_amount || 0,
							amount_paid: b.amount_paid || 0,
							amount_due: b.amount_due || 0,
							duration_minutes: b.duration_minutes || 0
						}));
				} else {
					pendingBookings = [];
				}
			} else {
				console.error('Failed to fetch pending bookings:', response.status);
			}
		} catch (err) {
			console.error('Error fetching pending bookings:', err);
		} finally {
			loadingBookings = false;
		}
	}

	// Fetch bookings when authorized
	$effect(() => {
		if (pageState === 'authorized') {
			fetchPendingBookings();
		}
	});
</script>

{#if pageState === 'loading'}
	<!-- Full page skeleton loading -->
	<div class="mx-auto max-w-6xl space-y-6 p-6">
		<!-- Header Skeleton -->
		<div class="mb-8 flex items-center justify-center text-center">
			<div class="space-y-2">
				<Skeleton class="h-8 w-64" />
				<Skeleton class="h-4 w-96" />
			</div>
		</div>

		<!-- Card Grid Skeleton -->
		<div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
			{#each Array(3) as _, i (i)}
				<Card.Root>
					<Card.Header>
						<Skeleton class="h-6 w-32" />
						<Skeleton class="h-4 w-48" />
					</Card.Header>
					<Card.Content class="space-y-4">
						<Skeleton class="h-32 w-full" />
						<div class="flex justify-end">
							<Skeleton class="h-10 w-24" />
						</div>
					</Card.Content>
				</Card.Root>
			{/each}
		</div>

		<!-- Table Skeleton -->
		<Card.Root>
			<Card.Header>
				<Skeleton class="h-6 w-32" />
				<Skeleton class="h-4 w-64" />
			</Card.Header>
			<Card.Content class="space-y-4">
				<div class="flex justify-between">
					<Skeleton class="h-10 w-32" />
					<Skeleton class="h-10 w-24" />
				</div>
				<div class="hidden w-full overflow-x-auto md:block">
					<table class="w-full table-auto border-collapse text-sm">
						<thead>
							<tr class="border-b text-left text-xs text-gray-500">
								{#each Array(4) as _, i (i)}
									<th class="py-3"><Skeleton class="h-4 w-20" /></th>
								{/each}
							</tr>
						</thead>
						<tbody>
							{#each Array(5) as _, i (i)}
								<tr class="border-b">
									{#each Array(4) as _, j (j)}
										<td class="py-3"><Skeleton class="h-4 w-24" /></td>
									{/each}
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</Card.Content>
		</Card.Root>
	</div>
{:else if pageState === 'authorized'}
	<!-- Main Dashboard Content -->
	<div class="mx-auto max-w-6xl space-y-6 p-6">
		<!-- Header -->
		<div class="mb-8 flex items-center justify-center text-center">
			<div>
				<h1 class="text-3xl font-bold">Needs Attention</h1>
				<p class="text-gray-600">Pending bookings requiring confirmation or action</p>
			</div>
		</div>

		<!-- Stats Cards Example -->
		<div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
			<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"
									viewBox="0 0 24 24"
									fill="none"
									stroke="currentColor"
									stroke-width="2"
								>
									<rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
									<line x1="16" y1="2" x2="16" y2="6" />
									<line x1="8" y1="2" x2="8" y2="6" />
									<line x1="3" y1="10" x2="21" y2="10" />
								</svg>
								Pending Bookings
							</Card.Title>
							<Card.Description>Awaiting confirmation</Card.Description>
						</div>
						<div class="rounded-full bg-amber-100 px-3 py-1">
							<span class="text-lg font-bold text-amber-700">
								{loadingBookings ? '...' : pendingBookings.length}
							</span>
						</div>
					</div>
				</Card.Header>
			</Card.Root>
		</div>

		<!-- Main Content Cards -->
		<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
			<!-- Example Management Card 1 -->
			<Card.Root class="h-full">
				<Card.Header>
					<div class="flex items-start justify-between">
						<div>
							<Card.Title>Recent Activity</Card.Title>
							<Card.Description>Latest actions and updates</Card.Description>
						</div>
						<Button variant="outline" size="sm">View All</Button>
					</div>
				</Card.Header>
				<Card.Content class="space-y-4">
					<div class="space-y-2">
						{#each Array(4) as _, i (i)}
							<div class="flex items-center justify-between rounded bg-gray-50 p-3">
								<div class="flex items-center gap-3">
									<div class="h-10 w-10 rounded-full bg-gray-200"></div>
									<div>
										<div class="font-medium">Activity {i + 1}</div>
										<div class="text-xs text-gray-500">2 hours ago</div>
									</div>
								</div>
								<Button variant="ghost" size="sm">View</Button>
							</div>
						{/each}
					</div>
				</Card.Content>
			</Card.Root>

			<!-- Example Management Card 2 -->
			<Card.Root class="h-full">
				<Card.Header>
					<div class="flex items-start justify-between">
						<div>
							<Card.Title>Quick Actions</Card.Title>
							<Card.Description>Common administrative tasks</Card.Description>
						</div>
					</div>
				</Card.Header>
				<Card.Content class="space-y-3">
					<Button class="w-full justify-start" variant="outline">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="mr-2 h-4 w-4"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
						>
							<line x1="12" y1="5" x2="12" y2="19" />
							<line x1="5" y1="12" x2="19" y2="12" />
						</svg>
						Add New Item
					</Button>
					<Button class="w-full justify-start" variant="outline">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="mr-2 h-4 w-4"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
						>
							<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
							<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
						</svg>
						Edit Settings
					</Button>
					<Button class="w-full justify-start" variant="outline">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="mr-2 h-4 w-4"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
						>
							<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
							<polyline points="7 10 12 15 17 10" />
							<line x1="12" y1="15" x2="12" y2="3" />
						</svg>
						Export Data
					</Button>
					<Button class="w-full justify-start" variant="outline">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="mr-2 h-4 w-4"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
						>
							<circle cx="12" cy="12" r="3" />
							<path
								d="M12 1v6m0 6v6m5.2-13.2l-4.2 4.2m0 6l4.2 4.2M23 12h-6m-6 0H1m20.2-5.2l-4.2 4.2m0 6l4.2 4.2"
							/>
						</svg>
						View Reports
					</Button>
				</Card.Content>
			</Card.Root>
		</div>

		<!-- Data Table Example -->
		<Card.Root>
			<Card.Header>
				<div class="flex items-center justify-between">
					<div>
						<Card.Title>Data Management</Card.Title>
						<Card.Description>View and manage your data</Card.Description>
					</div>
					<Button>
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="mr-2 h-4 w-4"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
						>
							<line x1="12" y1="5" x2="12" y2="19" />
							<line x1="5" y1="12" x2="19" y2="12" />
						</svg>
						Add New
					</Button>
				</div>
			</Card.Header>

			<Card.Content class="space-y-4">
				<!-- Desktop Table -->
				<div class="hidden w-full overflow-x-auto md:block">
					<table class="w-full table-auto border-collapse text-sm">
						<thead>
							<tr class="border-b text-left text-xs text-gray-500">
								<th class="py-3 font-medium">Name</th>
								<th class="py-3 font-medium">Status</th>
								<th class="py-3 font-medium">Date</th>
								<th class="py-3 text-center font-medium">Actions</th>
							</tr>
						</thead>
						<tbody>
							{#each Array(5) as _, i (i)}
								<tr class="border-b hover:bg-gray-50">
									<td class="py-3 font-medium">Item {i + 1}</td>
									<td class="py-3">
										<span
											class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {i %
												2 ===
											0
												? 'bg-emerald-100 text-emerald-800'
												: 'bg-amber-100 text-amber-800'}"
										>
											{i % 2 === 0 ? 'Active' : 'Pending'}
										</span>
									</td>
									<td class="py-3 text-gray-600">2024-01-{String(i + 1).padStart(2, '0')}</td>
									<td class="py-3">
										<div class="flex justify-center gap-2">
											<Button variant="outline" size="sm">Edit</Button>
											<Button variant="destructive" size="sm">Delete</Button>
										</div>
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>

				<!-- Mobile Cards -->
				<div class="space-y-4 md:hidden">
					{#each Array(5) as _, i (i)}
						<div class="rounded-lg border p-4 hover:bg-gray-50">
							<div class="space-y-3">
								<div class="flex items-start justify-between">
									<h3 class="font-medium">Item {i + 1}</h3>
									<span
										class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {i %
											2 ===
										0
											? 'bg-emerald-100 text-emerald-800'
											: 'bg-amber-100 text-amber-800'}"
									>
										{i % 2 === 0 ? 'Active' : 'Pending'}
									</span>
								</div>

								<div class="text-sm text-gray-600">
									Date: 2024-01-{String(i + 1).padStart(2, '0')}
								</div>

								<div class="flex gap-2 pt-2">
									<Button variant="outline" size="sm" class="flex-1">Edit</Button>
									<Button variant="destructive" size="sm" class="flex-1">Delete</Button>
								</div>
							</div>
						</div>
					{/each}
				</div>
			</Card.Content>
		</Card.Root>
	</div>
{/if}
