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

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

	let event = $derived(data.event);
	let eventColor = $derived(getEventColor(event.colorId));

	// Edit mode
	let isEditing = $state(false);
	let isSaving = $state(false);
	let isDeleting = $state(false);

	// Edit form state
	let editSummary = $state('');
	let editDescription = $state('');
	let editLocation = $state('');
	let editColorId = $state('');
	let editStartDateTime = $state('');
	let editEndDateTime = $state('');
	let editAllDay = $state(false);
	let editStartDate = $state('');
	let editEndDate = $state('');

	function startEditing() {
		editSummary = event.summary;
		editDescription = event.description ?? '';
		editLocation = event.location ?? '';
		editColorId = event.colorId ?? '';
		editAllDay = !!event.start.date;

		if (event.start.date) {
			editStartDate = event.start.date;
			editEndDate = event.end.date ?? event.start.date;
		} else if (event.start.dateTime) {
			editStartDateTime = formatDateTimeLocal(event.start.dateTime);
			editEndDateTime = event.end.dateTime ? formatDateTimeLocal(event.end.dateTime) : '';
		}

		isEditing = true;
	}

	function cancelEditing() {
		isEditing = false;
	}

	function formatDateTimeLocal(isoString: string): string {
		const date = new Date(isoString);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day}T${hours}:${minutes}`;
	}

	async function handleSave() {
		isSaving = true;
		try {
			const input: UpdateCalendarEventInput = {
				summary: editSummary,
				description: editDescription || undefined,
				location: editLocation || undefined,
				colorId: editColorId || undefined
			};

			if (editAllDay) {
				input.start = { date: editStartDate };
				input.end = { date: editEndDate };
			} else {
				input.start = { dateTime: new Date(editStartDateTime).toISOString() };
				input.end = { dateTime: new Date(editEndDateTime).toISOString() };
			}

			await client.mutate({
				mutation: UPDATE_CALENDAR_EVENT,
				variables: {
					eventId: event.id,
					input
				}
			});

			isEditing = false;
			await invalidateAll();
		} catch (err) {
			console.error('Failed to update event:', err);
			alert('Failed to update event');
		} finally {
			isSaving = false;
		}
	}

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

		isDeleting = true;
		try {
			await client.mutate({
				mutation: DELETE_CALENDAR_EVENT,
				variables: { eventId: event.id }
			});
			goto('/admin/calendar');
		} catch (err) {
			console.error('Failed to delete event:', err);
			alert('Failed to delete event');
			isDeleting = false;
		}
	}

	// Format display
	function formatDateTime(event: CalendarEvent): string {
		if (event.start.date) {
			const start = new Date(event.start.date + 'T00:00:00');
			if (event.end.date && event.end.date !== event.start.date) {
				const end = new Date(event.end.date + 'T00:00:00');
				return `${start.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })} - ${end.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })}`;
			}
			return (
				start.toLocaleDateString('en-US', {
					weekday: 'long',
					month: 'long',
					day: 'numeric',
					year: 'numeric'
				}) + ' (All day)'
			);
		}

		if (event.start.dateTime) {
			const start = new Date(event.start.dateTime);
			const dateStr = start.toLocaleDateString('en-US', {
				weekday: 'long',
				month: 'long',
				day: 'numeric',
				year: 'numeric'
			});
			const startTime = start.toLocaleTimeString('en-US', {
				hour: 'numeric',
				minute: '2-digit',
				hour12: true
			});

			if (event.end.dateTime) {
				const end = new Date(event.end.dateTime);
				const endTime = end.toLocaleTimeString('en-US', {
					hour: 'numeric',
					minute: '2-digit',
					hour12: true
				});
				return `${dateStr}, ${startTime} - ${endTime}`;
			}

			return `${dateStr}, ${startTime}`;
		}

		return 'Unknown';
	}
</script>

<svelte:head>
	<title>{event.summary} - Calendar - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<div class="mb-6 flex items-start justify-between gap-4">
			<div class="flex items-start gap-4">
				<a
					href="/admin/calendar"
					class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
					aria-label="Back to calendar"
				>
					<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="M15 19l-7-7 7-7"
						/>
					</svg>
				</a>
				<div>
					<div class="flex items-center gap-3">
						{#if eventColor}
							<span class="h-4 w-4 shrink-0 rounded-full {eventColor.bg}" title={eventColor.name}
							></span>
						{/if}
						<h1 class="text-2xl font-bold text-accent7-600 md:text-3xl dark:text-accent7-400">
							{event.summary}
						</h1>
					</div>
					{#if event.status === 'cancelled'}
						<span
							class="mt-2 inline-flex rounded-full bg-error-100 px-2.5 py-0.5 text-xs font-medium text-error-800 dark:bg-error-900/30 dark:text-error-400"
						>
							Cancelled
						</span>
					{/if}
				</div>
			</div>

			{#if !isEditing}
				<div class="flex gap-2">
					<button type="button" onclick={startEditing} class="btn-outline"> Edit </button>
					<button
						type="button"
						onclick={handleDelete}
						disabled={isDeleting}
						class="btn-outline text-error-600 hover:bg-error-50 dark:text-error-400 dark:hover:bg-error-900/20"
					>
						{isDeleting ? 'Deleting...' : 'Delete'}
					</button>
				</div>
			{/if}
		</div>

		{#if isEditing}
			<!-- Edit Form -->
			<div class="rounded-xl border border-theme bg-theme p-6">
				<h2 class="mb-4 text-lg font-semibold text-theme">Edit Event</h2>

				<div class="space-y-4">
					<label class="block">
						<span class="text-sm font-medium text-theme">Summary</span>
						<input
							type="text"
							bind:value={editSummary}
							class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
							required
						/>
					</label>

					<label class="block">
						<span class="text-sm font-medium text-theme">Description</span>
						<textarea
							bind:value={editDescription}
							rows="3"
							class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
						></textarea>
					</label>

					<label class="block">
						<span class="text-sm font-medium text-theme">Location</span>
						<input
							type="text"
							bind:value={editLocation}
							class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
						/>
					</label>

					<label class="block">
						<span class="text-sm font-medium text-theme">Color</span>
						<select
							bind:value={editColorId}
							class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
						>
							<option value="">Default</option>
							{#each EVENT_COLORS as color (color.id)}
								<option value={color.id} selected={editColorId === color.id}>{color.name}</option>
							{/each}
						</select>
					</label>

					<label class="flex items-center gap-2">
						<input
							type="checkbox"
							bind:checked={editAllDay}
							class="h-4 w-4 rounded border-theme text-accent7-500 focus:ring-accent7-500"
						/>
						<span class="text-sm font-medium text-theme">All day event</span>
					</label>

					{#if editAllDay}
						<div class="grid gap-4 sm:grid-cols-2">
							<label class="block">
								<span class="text-sm font-medium text-theme">Start Date</span>
								<input
									type="date"
									bind:value={editStartDate}
									class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
									required
								/>
							</label>
							<label class="block">
								<span class="text-sm font-medium text-theme">End Date</span>
								<input
									type="date"
									bind:value={editEndDate}
									class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
									required
								/>
							</label>
						</div>
					{:else}
						<div class="grid gap-4 sm:grid-cols-2">
							<label class="block">
								<span class="text-sm font-medium text-theme">Start</span>
								<input
									type="datetime-local"
									bind:value={editStartDateTime}
									class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
									required
								/>
							</label>
							<label class="block">
								<span class="text-sm font-medium text-theme">End</span>
								<input
									type="datetime-local"
									bind:value={editEndDateTime}
									class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
									required
								/>
							</label>
						</div>
					{/if}

					<div class="flex justify-end gap-3 pt-4">
						<button type="button" onclick={cancelEditing} class="btn-outline" disabled={isSaving}>
							Cancel
						</button>
						<button type="button" onclick={handleSave} class="btn-accent7" disabled={isSaving}>
							{isSaving ? 'Saving...' : 'Save Changes'}
						</button>
					</div>
				</div>
			</div>
		{:else}
			<!-- View Mode -->
			<div class="rounded-xl border border-theme bg-theme p-6">
				<div class="space-y-6">
					<!-- Date & Time -->
					<div>
						<h2 class="text-sm font-medium text-theme-secondary">Date & Time</h2>
						<p class="mt-1 text-theme">{formatDateTime(event)}</p>
					</div>

					<!-- Location -->
					{#if event.location}
						<div>
							<h2 class="text-sm font-medium text-theme-secondary">Location</h2>
							<p class="mt-1 text-theme">{event.location}</p>
						</div>
					{/if}

					<!-- Description -->
					{#if event.description}
						<div>
							<h2 class="text-sm font-medium text-theme-secondary">Description</h2>
							<p class="mt-1 whitespace-pre-wrap text-theme">{event.description}</p>
						</div>
					{/if}

					<!-- Attendees -->
					{#if event.attendees && event.attendees.length > 0}
						<div>
							<h2 class="text-sm font-medium text-theme-secondary">Attendees</h2>
							<ul class="mt-2 space-y-2">
								{#each event.attendees as attendee (attendee.email)}
									<li class="flex items-center gap-2">
										<div
											class="flex h-8 w-8 items-center justify-center rounded-full bg-accent7-100 text-sm font-medium text-accent7-600 dark:bg-accent7-900/30 dark:text-accent7-400"
										>
											{(attendee.displayName ?? attendee.email).charAt(0).toUpperCase()}
										</div>
										<div>
											<p class="text-sm font-medium text-theme">
												{attendee.displayName ?? attendee.email}
											</p>
											{#if attendee.displayName}
												<p class="text-xs text-theme-secondary">{attendee.email}</p>
											{/if}
										</div>
										{#if attendee.responseStatus}
											<span class="ml-auto text-xs text-theme-muted capitalize">
												{attendee.responseStatus}
											</span>
										{/if}
									</li>
								{/each}
							</ul>
						</div>
					{/if}

					<!-- Google Calendar Link -->
					{#if event.htmlLink}
						<div>
							<a
								href={event.htmlLink}
								target="_blank"
								rel="noopener noreferrer"
								class="inline-flex items-center gap-2 text-sm text-accent7-600 hover:text-accent7-700 dark:text-accent7-400 dark:hover:text-accent7-300"
							>
								<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="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
									/>
								</svg>
								View in Google Calendar
							</a>
						</div>
					{/if}

					<!-- Metadata -->
					<div class="border-t border-theme pt-4">
						<div class="flex flex-wrap gap-6 text-xs text-theme-muted">
							{#if event.created}
								<span>Created: {new Date(event.created).toLocaleDateString()}</span>
							{/if}
							{#if event.updated}
								<span>Updated: {new Date(event.updated).toLocaleDateString()}</span>
							{/if}
							<span>ID: {event.id}</span>
						</div>
					</div>
				</div>
			</div>
		{/if}
	</ContentContainer>
</div>
