<script lang="ts">
	import { goto, invalidateAll } from '$app/navigation';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { MonthSelector, AdminDashboardHeader } from '$lib/components/admin';
	import { client } from '$lib/graphql/client';
	import { DELETE_CALENDAR_EVENT } from '$lib/graphql/mutations/calendar';
	import { getEventColor, type CalendarEvent } from '$lib/graphql/queries/calendar';

	let { data }: { data: PageData } = $props();

	// Local search filter
	let searchQuery = $state('');

	// Time filter
	let timeFilter = $state<'all' | 'upcoming' | 'past'>('all');

	// Deleting state
	let deletingId = $state<string | null>(null);

	// Get event date for filtering
	function getEventDate(event: CalendarEvent): Date {
		if (event.start.dateTime) {
			return new Date(event.start.dateTime);
		}
		if (event.start.date) {
			return new Date(event.start.date + 'T00:00:00');
		}
		return new Date();
	}

	// Filter by search query
	let searchFiltered = $derived.by(() => {
		if (!searchQuery.trim()) return data.events;

		const query = searchQuery.toLowerCase();
		return data.events.filter(
			(e) =>
				e.summary.toLowerCase().includes(query) ||
				e.description?.toLowerCase().includes(query) ||
				e.location?.toLowerCase().includes(query) ||
				e.attendees?.some(
					(a) =>
						a.email.toLowerCase().includes(query) || a.displayName?.toLowerCase().includes(query)
				)
		);
	});

	// Filter by time
	let filteredEvents = $derived.by(() => {
		if (timeFilter === 'all') return searchFiltered;

		const now = new Date();
		return searchFiltered.filter((e) => {
			const eventDate = getEventDate(e);
			if (timeFilter === 'past') {
				return eventDate < now;
			}
			// upcoming
			return eventDate >= now;
		});
	});

	// Group events by date
	let eventsByDate = $derived.by(() => {
		const grouped: Record<string, CalendarEvent[]> = {};

		for (const event of filteredEvents) {
			const dateKey = getEventDateKey(event);
			if (!grouped[dateKey]) {
				grouped[dateKey] = [];
			}
			grouped[dateKey].push(event);
		}

		return Object.entries(grouped).sort((a, b) => a[0].localeCompare(b[0]));
	});

	// Get the date key for grouping (YYYY-MM-DD)
	function getEventDateKey(event: CalendarEvent): string {
		if (event.start.date) {
			return event.start.date;
		}
		if (event.start.dateTime) {
			return event.start.dateTime.split('T')[0];
		}
		return 'Unknown';
	}

	// Format date for section headers
	function formatDateHeader(dateStr: string): string {
		if (dateStr === 'Unknown') return 'Unknown Date';

		const date = new Date(dateStr + 'T00:00:00');
		const now = Date.now();
		const todayStart = now - (now % 86400000);

		const dateTime = date.getTime();
		if (dateTime >= todayStart && dateTime < todayStart + 86400000) {
			return 'Today';
		}
		if (dateTime >= todayStart + 86400000 && dateTime < todayStart + 172800000) {
			return 'Tomorrow';
		}

		return date.toLocaleDateString('en-US', {
			weekday: 'long',
			month: 'long',
			day: 'numeric',
			year: 'numeric'
		});
	}

	// Format time for event display
	function formatEventTime(event: CalendarEvent): string {
		if (event.start.date) {
			return 'All day';
		}
		if (event.start.dateTime) {
			const start = new Date(event.start.dateTime);
			const end = event.end?.dateTime ? new Date(event.end.dateTime) : null;

			const startStr = start.toLocaleTimeString('en-US', {
				hour: 'numeric',
				minute: '2-digit',
				hour12: true
			});

			if (end) {
				const endStr = end.toLocaleTimeString('en-US', {
					hour: 'numeric',
					minute: '2-digit',
					hour12: true
				});
				return `${startStr} - ${endStr}`;
			}

			return startStr;
		}
		return '';
	}

	async function handleDelete(eventId: string) {
		if (!confirm('Delete this event? This cannot be undone.')) {
			return;
		}

		deletingId = eventId;
		try {
			await client.mutate({
				mutation: DELETE_CALENDAR_EVENT,
				variables: { eventId }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete event:', err);
			alert('Failed to delete event');
		} finally {
			deletingId = null;
		}
	}

	// Tab counts
	let tabCounts = $derived.by(() => {
		const now = new Date();
		let upcoming = 0;
		let past = 0;

		for (const e of searchFiltered) {
			const eventDate = getEventDate(e);
			if (eventDate < now) {
				past++;
			} else {
				upcoming++;
			}
		}

		return { all: searchFiltered.length, upcoming, past };
	});
</script>

<svelte:head>
	<title>Calendar - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader title="Calendar" subtitle="{data.events.length} events for {data.month}">
			{#snippet actions()}
				<a
					href="/admin/calendar/new"
					class="btn-accent7 flex w-full items-center justify-center gap-2 sm:w-auto sm:justify-start"
				>
					<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					Create Event
				</a>
			{/snippet}
		</AdminDashboardHeader>

		<!-- Month Selector -->
		<div class="mb-6">
			<MonthSelector month={data.month} />
		</div>

		<!-- Error State -->
		{#if data.error}
			<div class="mb-6 rounded-lg border border-error-500/30 bg-error-500/10 p-4">
				<div class="flex items-center gap-3">
					<svg
						class="h-5 w-5 shrink-0 text-error-600 dark:text-error-400"
						fill="none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
						/>
					</svg>
					<div>
						<p class="font-medium text-error-600 dark:text-error-400">
							Failed to load calendar events
						</p>
						<p class="text-sm text-error-600/80 dark:text-error-400/80">
							{data.error}
						</p>
					</div>
				</div>
			</div>
		{/if}

		<!-- Search -->
		<div class="mb-6">
			<div class="relative">
				<svg
					class="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<input
					type="text"
					bind:value={searchQuery}
					placeholder="Search events..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme py-2 pr-4 pl-10 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
				/>
			</div>
		</div>

		<!-- Time Filter Tabs -->
		<div class="mb-6 flex gap-1 rounded-lg bg-black/5 p-1 dark:bg-white/5" role="tablist">
			{#each [{ id: 'all', label: 'All' }, { id: 'upcoming', label: 'Upcoming' }, { id: 'past', label: 'Past' }] as tab (tab.id)}
				{@const isActive = timeFilter === tab.id}
				{@const count = tabCounts[tab.id as keyof typeof tabCounts]}
				<button
					type="button"
					onclick={() => (timeFilter = tab.id as typeof timeFilter)}
					class="flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors
						{isActive
						? 'bg-accent7-500/15 text-accent7-600 dark:text-accent7-400'
						: 'text-theme-secondary hover:bg-black/5 hover:text-theme dark:hover:bg-white/5'}"
					role="tab"
					aria-selected={isActive}
				>
					{tab.label}
					<span
						class="ml-1.5 rounded-full px-1.5 py-0.5 text-xs
							{isActive ? 'bg-accent7-500/20' : 'bg-black/5 dark:bg-white/5'}"
					>
						{count}
					</span>
				</button>
			{/each}
		</div>

		<!-- Events List -->
		{#if eventsByDate.length > 0}
			<div class="space-y-8">
				{#each eventsByDate as [dateKey, dateEvents] (dateKey)}
					<div>
						<!-- Date Header -->
						<div class="mb-4 flex items-center gap-3">
							<div class="h-px flex-1 bg-accent7-500/20"></div>
							<h2 class="text-sm font-semibold text-accent7-600 dark:text-accent7-400">
								{formatDateHeader(dateKey)}
							</h2>
							<div class="h-px flex-1 bg-accent7-500/20"></div>
						</div>

						<!-- Events for this date -->
						<div class="space-y-3">
							{#each dateEvents as event (event.id)}
								{@const eventColor = getEventColor(event.colorId)}
								<div class="group relative card-calendar">
									<a href="/admin/calendar/{event.id}" class="block">
										<div class="flex items-start justify-between gap-4">
											<div class="min-w-0 flex-1 space-y-2">
												<!-- Event Title -->
												<div class="flex flex-wrap items-center gap-3">
													{#if eventColor}
														<span
															class="h-3 w-3 shrink-0 rounded-full {eventColor.bg}"
															title={eventColor.name}
														></span>
													{/if}
													<h3 class="text-lg font-semibold text-accent7-600 dark:text-accent7-400">
														{event.summary}
													</h3>
													{#if event.start.date}
														<span
															class="inline-flex items-center rounded-full bg-accent7-500/10 px-2.5 py-0.5 text-xs font-medium text-accent7-600 dark:text-accent7-400"
														>
															All Day
														</span>
													{/if}
												</div>

												<!-- Event Details -->
												<div class="flex flex-wrap items-center gap-4 text-sm text-theme-secondary">
													<!-- Time -->
													<span class="flex items-center gap-1.5">
														<svg
															class="h-4 w-4"
															fill="none"
															stroke="currentColor"
															viewBox="0 0 24 24"
														>
															<path
																stroke-linecap="round"
																stroke-linejoin="round"
																stroke-width="2"
																d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
															/>
														</svg>
														{formatEventTime(event)}
													</span>

													<!-- Location -->
													{#if event.location}
														<span class="flex items-center gap-1.5">
															<svg
																class="h-4 w-4"
																fill="none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
																/>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
																/>
															</svg>
															{event.location}
														</span>
													{/if}

													<!-- Attendees count -->
													{#if event.attendees && event.attendees.length > 0}
														<span class="hidden items-center gap-1.5 sm:flex">
															<svg
																class="h-4 w-4"
																fill="none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
																/>
															</svg>
															{event.attendees.length} attendee{event.attendees.length !== 1
																? 's'
																: ''}
														</span>
													{/if}
												</div>

												<!-- Description preview -->
												{#if event.description}
													<p class="line-clamp-2 hidden text-sm text-theme-muted sm:block">
														{event.description}
													</p>
												{/if}
											</div>

											<!-- Chevron -->
											<svg
												class="mt-1 h-5 w-5 shrink-0 text-theme-muted"
												fill="none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M9 5l7 7-7 7"
												/>
											</svg>
										</div>
									</a>

									<!-- Delete button (appears on hover) -->
									<button
										type="button"
										onclick={() => handleDelete(event.id)}
										disabled={deletingId === event.id}
										class="absolute top-3 right-10 hidden rounded p-1 text-theme-muted group-hover:block hover:bg-error-100 hover:text-error-600 dark:hover:bg-error-900/30 dark:hover:text-error-400"
										aria-label="Delete event"
									>
										{#if deletingId === event.id}
											<svg
												class="h-4 w-4 animate-spin"
												viewBox="0 0 24 24"
												fill="none"
												stroke="currentColor"
											>
												<circle cx="12" cy="12" r="10" stroke-width="4" class="opacity-25"></circle>
												<path stroke-width="4" d="M4 12a8 8 0 018-8" class="opacity-75"></path>
											</svg>
										{:else}
											<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
												/>
											</svg>
										{/if}
									</button>
								</div>
							{/each}
						</div>
					</div>
				{/each}
			</div>
		{:else if searchQuery}
			<div class="rounded-lg border border-theme bg-theme-secondary py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<h3 class="mt-4 text-lg font-medium text-theme">No Events Found</h3>
				<p class="mt-2 text-theme-secondary">
					No events match "{searchQuery}". Try a different search term.
				</p>
				<button
					type="button"
					onclick={() => (searchQuery = '')}
					class="mt-4 text-accent7-500 hover:text-accent7-600"
				>
					Clear search
				</button>
			</div>
		{:else}
			<div class="rounded-lg border border-theme bg-theme-secondary py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						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>
				<h3 class="mt-4 text-lg font-medium text-theme">No Events</h3>
				<p class="mt-2 text-theme-secondary">No events scheduled for this month.</p>
				<a
					href="/admin/calendar/new"
					class="mt-4 inline-flex items-center gap-2 rounded-lg bg-accent7-500 px-4 py-2 text-white transition-colors hover:bg-accent7-600"
				>
					<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					Create Event
				</a>
			</div>
		{/if}
	</ContentContainer>
</div>
