<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 CallInBooking from '$lib/components/admin/CallInBooking.svelte';
	import WalkInBooking from '$lib/components/admin/WalkInBooking.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';
			goto('/login', { replaceState: true });
			return;
		}

		if (authStore.currentUser?.role !== 'admin') {
			pageState = 'unauthorized';
			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);

	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>

{#if pageState === 'loading'}
	<div class="mx-auto max-w-7xl space-y-6 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-6">
		<!-- Header -->
		<div class="mb-6">
			<h1 class="text-3xl font-bold">Today's Schedule</h1>
			<p class="text-gray-600">{dateString}</p>
		</div>

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

		<!-- quick booking Grid -->
		<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
			<!-- Left Column: Create a booking for a call in or messaging user  (2/3 width on large screens) -->
			<div class="lg:col-span-2">
				<WalkInBooking />
			</div>

			<!-- Right Column: Similar to the above but immediately block out my next availible working space while I talk over the walk-in users needs and chat etc (1/3 width on large screens) -->
			<div class="space-y-6">
				<CallInBooking />
			</div>
		</div>

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

			<!-- Right Column: Quick Info Panels (1/3 width on large screens) -->
			<div class="space-y-6">
				<!-- 3 oldest pending appointments for approval -->
				<PendingApprovals {openBookingModal} />
			</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 -->
	{#if showBookingModal && selectedBookingId}
		<BookingModal bind:open={showBookingModal} bookingId={selectedBookingId} />
	{/if}

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

	{#if showUserModal && selectedUserId}
		<UserModal bind:open={showUserModal} userId={selectedUserId} {openBookingModal} />
	{/if}
{/if}
