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

	// Component imports
	import CurrentAppointment from '$lib/components/today/CurrentAppointment.svelte';
	import TodayCalendar from '$lib/components/today/TodayCalendar.svelte';
	import PendingApprovals from '$lib/components/today/PendingApprovals.svelte';
	import TodayStats from '$lib/components/today/TodayStats.svelte';
	import CallInBooking from '$lib/components/admin/CallInBooking.svelte';
	import WalkInBooking from '$lib/components/admin/WalkInBooking.svelte';
	import TillPurchases from '$lib/components/admin/TillPurchases.svelte';
	import BookingModal from '$lib/components/admin/BookingModal.svelte';
	import EditBookingModal from '$lib/components/admin/EditBookingModal.svelte';
	import UserModal from '$lib/components/admin/UserModal.svelte';

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

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

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

		if (!authStore.isAuthenticated) {
			pageState = 'unauthorized';
			// eslint-disable-next-line svelte/no-navigation-without-resolve
			goto('/login', { replaceState: true });
			return;
		}

		if (authStore.currentUser?.role !== 'admin') {
			pageState = 'unauthorized';
			// eslint-disable-next-line svelte/no-navigation-without-resolve
			goto('/', { replaceState: true });
			return;
		}

		pageState = 'authorized';
	});

	// =============== Modal State ===============
	let showBookingModal = $state(false);
	let showEditBookingModal = $state(false);
	let showUserModal = $state(false);
	let selectedBookingId = $state<string | null>(null);
	let selectedUserId = $state<string | null>(null);
	let editBookingNextStart = $state<string | null>(null);
	let hasItems = $state(false);

	function openBookingModal(bookingId: string) {
		selectedBookingId = bookingId;
		showBookingModal = true;
	}

	function openEditBookingModal(bookingId: string, nextAppointmentStart: string | null = null) {
		selectedBookingId = bookingId;
		editBookingNextStart = nextAppointmentStart;
		showEditBookingModal = true;
	}

	function openUserModal(userId: string) {
		selectedUserId = userId;
		showUserModal = true;
	}

	// Get current date string for display
	const today = new SvelteDate();
	const dateString = today.toLocaleDateString('en-US', {
		weekday: 'long',
		year: 'numeric',
		month: 'long',
		day: 'numeric'
	});
</script>

<svelte:head>
	<script>
		(function () {
			// Pre-hydration auth guard: reads localStorage directly because the Svelte
			// authStore hasn't initialized yet at this point (async+$state). This runs
			// synchronously in <svelte:head> before any rendering, preventing a flash
			// of protected content. The authStore handles post-hydration auth.
			try {
				var token = localStorage.getItem('authToken');
				if (!token) {
					window.location.replace('/login');
					return;
				}
				var payload = JSON.parse(atob(token.split('.')[1]));
				if (payload.exp * 1000 <= Date.now()) {
					window.location.replace('/login');
					return;
				}
				if (payload.role !== 'admin') {
					window.location.replace('/');
				}
			} catch (e) {
				window.location.replace('/login');
			}
		})();
	</script>
</svelte:head>

{#if pageState === 'loading'}
	<div class="mx-auto max-w-7xl space-y-6 p-4 md:p-6">
		<!-- Header Skeleton -->
		<div class="mb-6">
			<Skeleton class="h-8 w-64" />
			<Skeleton class="mt-2 h-4 w-96" />
		</div>

		<!-- Current Appointment Skeleton -->
		<Skeleton class="h-64 w-full" />

		<!-- Grid Skeleton -->
		<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
			<div class="lg:col-span-2">
				<Skeleton class="h-96 w-full" />
			</div>
			<div class="space-y-6">
				<Skeleton class="h-48 w-full" />
				<Skeleton class="h-48 w-full" />
			</div>
		</div>

		<!-- Bottom Grid Skeleton -->
		<div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
			<Skeleton class="h-64 w-full" />
			<Skeleton class="h-64 w-full" />
			<Skeleton class="h-64 w-full" />
		</div>
	</div>
{:else if pageState === 'authorized'}
	<div class="mx-auto max-w-7xl space-y-6 p-4 md:p-6">
		<!-- Header -->
		<div class="mb-6">
			<h1 class="font-['Playfair_Display'] text-4xl font-bold">Today's Schedule</h1>
			<p class="text-gray-600">{dateString}</p>
		</div>

		<!-- Current/Next Appointment Card (Full Width) -->
		<CurrentAppointment
			_openBookingModal={openBookingModal}
			{openEditBookingModal}
			{openUserModal}
		/>

		<!-- Quick Booking + Till Purchases Grid -->
		<div class="grid grid-cols-1 gap-4 lg:grid-cols-2 lg:gap-6">
			<div class="space-y-4">
				<CallInBooking />
				<WalkInBooking />
			</div>
			<div>
				<TillPurchases />
			</div>
		</div>

		<!-- Main Content Grid -->
		<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
			<!-- Today's Calendar (2/3 width on desktop, second on mobile) -->
			<div class="order-2 lg:order-1 lg:col-span-2">
				<TodayCalendar {openBookingModal} {openUserModal} />
			</div>

			<!-- Pending Approvals (first on mobile, right column on desktop) -->
			<div class="order-1 lg:order-2">
				<div class={hasItems ? '' : 'hidden lg:block'}>
					<PendingApprovals {openBookingModal} bind:hasItems />
				</div>
			</div>

			<!-- Today's Stats (bottom on mobile, right column below approvals on desktop) -->
			<div class="order-3 lg:order-2">
				<TodayStats />
			</div>
		</div>

		<!-- Bottom Row: Additional Panels -->
		<div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
			<!-- Today's Revenue -->
			<!-- <TodayRevenue /> -->

			<!-- Loyalty point accumulations and redemptions today -->
			<!-- <LoyaltyStats {openUserModal} /> -->
		</div>
	</div>

	<!-- Modals -->
	<BookingModal bind:open={showBookingModal} bookingId={selectedBookingId ?? ''} />

	<EditBookingModal
		bind:open={showEditBookingModal}
		bookingId={selectedBookingId ?? ''}
		nextAppointmentStart={editBookingNextStart}
		onSaved={() => {
			// Refresh the page data after save
			showBookingModal = false;
		}}
	/>

	<UserModal bind:open={showUserModal} userId={selectedUserId ?? ''} {openBookingModal} />
{/if}
