<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import AdminPageHeader from '$lib/components/admin/AdminPageHeader.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import EventForm from '$lib/components/admin/calendar/EventForm.svelte';
	import { calendarService } from '$lib/services/calendar';
	import { goto, invalidateAll } from '$app/navigation';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import type { PageData } from './$types';

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

	let event = $derived(data.event);
	let teamProfiles = $derived(data.teamProfiles);

	let showDeleteModal = $state(false);
	let isDeleting = $state(false);

	// Format date for display
	function formatDateTime(eventDateTime: { dateTime?: string; date?: string } | undefined): string {
		if (!eventDateTime) return '—';

		if (eventDateTime.dateTime) {
			const dt = new Date(eventDateTime.dateTime);
			return dt.toLocaleString('en-US', {
				weekday: 'long',
				month: 'long',
				day: 'numeric',
				year: 'numeric',
				hour: 'numeric',
				minute: '2-digit',
				hour12: true
			});
		}

		if (eventDateTime.date) {
			const dt = new Date(eventDateTime.date + 'T00:00:00');
			return dt.toLocaleDateString('en-US', {
				weekday: 'long',
				month: 'long',
				day: 'numeric',
				year: 'numeric'
			});
		}

		return '—';
	}

	// Format reminder time
	function formatReminderTime(minutes: number): string {
		if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
		if (minutes < 1440) {
			const hours = Math.floor(minutes / 60);
			return `${hours} hour${hours !== 1 ? 's' : ''}`;
		}
		if (minutes < 10080) {
			const days = Math.floor(minutes / 1440);
			return `${days} day${days !== 1 ? 's' : ''}`;
		}
		const weeks = Math.floor(minutes / 10080);
		return `${weeks} week${weeks !== 1 ? 's' : ''}`;
	}

	// Get event duration
	let eventDuration = $derived.by(() => {
		if (event.start.date) {
			// All-day event
			const start = new Date(event.start.date);
			const end = event.end?.date ? new Date(event.end.date) : start;
			const days = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
			return days <= 1 ? 'All day' : `${days} days`;
		}

		if (event.start.dateTime && event.end?.dateTime) {
			const start = new Date(event.start.dateTime);
			const end = new Date(event.end.dateTime);
			const diffMs = end.getTime() - start.getTime();
			const diffMins = Math.round(diffMs / (1000 * 60));

			if (diffMins < 60) {
				return `${diffMins} minute${diffMins !== 1 ? 's' : ''}`;
			}

			const hours = Math.floor(diffMins / 60);
			const mins = diffMins % 60;
			if (mins === 0) {
				return `${hours} hour${hours !== 1 ? 's' : ''}`;
			}
			return `${hours}h ${mins}m`;
		}

		return '';
	});

	function showEditForm() {
		offCanvas.showRight({
			title: 'Edit Event',
			content: editFormContent
		});
	}

	async function handleSuccess() {
		await invalidateAll();
	}

	async function handleDelete() {
		isDeleting = true;
		try {
			const result = await calendarService.deleteEvent(event.id);
			if (result.error) {
				console.error('Failed to delete event:', result.error);
				alert('Failed to delete event: ' + result.error.message);
				return;
			}
			await goto('/admin/calendar', { invalidateAll: true });
		} catch (err) {
			console.error('Failed to delete event:', err);
			alert('Failed to delete event. Please try again.');
		} finally {
			isDeleting = false;
			showDeleteModal = false;
		}
	}
</script>

{#snippet editFormContent()}
	<EventForm {teamProfiles} {event} onSuccess={handleSuccess} />
{/snippet}

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

<div class="py-8">
	<ContentContainer>
		<AdminPageHeader
			title={event.summary}
			subtitle={formatDateTime(event.start)}
			colorScheme="accent7"
			backHref="/admin/calendar"
			onEdit={showEditForm}
		/>

		<!-- Event Details Card -->
		<div class="mb-6 card-padded">
			<h3 class="mb-4 text-sm font-medium text-theme-muted">Event Details</h3>

			<div class="space-y-4">
				<!-- Start Time -->
				<div class="flex items-center justify-between border-b border-theme py-3">
					<div class="flex items-center gap-3">
						<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent7-500/20">
							<svg
								class="h-5 w-5 text-accent7-600 dark:text-accent7-400"
								style="fill: none"
								stroke="currentColor"
								viewBox="0 0 24 24"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									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>
						</div>
						<div>
							<p class="text-sm text-theme-muted">Start</p>
							<p class="font-medium text-theme">{formatDateTime(event.start)}</p>
						</div>
					</div>
				</div>

				<!-- End Time -->
				<div class="flex items-center justify-between border-b border-theme py-3">
					<div class="flex items-center gap-3">
						<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent7-500/20">
							<svg
								class="h-5 w-5 text-accent7-600 dark:text-accent7-400"
								style="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>
						</div>
						<div>
							<p class="text-sm text-theme-muted">End</p>
							<p class="font-medium text-theme">{formatDateTime(event.end)}</p>
						</div>
					</div>
					{#if eventDuration}
						<span
							class="rounded-full bg-accent7-500/10 px-3 py-1 text-sm font-medium text-accent7-600 dark:text-accent7-400"
						>
							{eventDuration}
						</span>
					{/if}
				</div>

				<!-- Location -->
				{#if event.location}
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div
								class="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary-500/20"
							>
								<svg
									class="h-5 w-5 text-secondary-600 dark:text-secondary-400"
									style="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>
							</div>
							<div>
								<p class="text-sm text-theme-muted">Location</p>
								<p class="font-medium text-theme">{event.location}</p>
							</div>
						</div>
					</div>
				{/if}

				<!-- Google Calendar Link -->
				{#if event.htmlLink}
					<div class="flex items-center justify-between py-3">
						<div class="flex items-center gap-3">
							<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-primary-500/20">
								<svg
									class="h-5 w-5 text-primary-600 dark:text-primary-400"
									style="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>
							</div>
							<div>
								<p class="text-sm text-theme-muted">View in Google Calendar</p>
								<a
									href={event.htmlLink}
									target="_blank"
									rel="noopener noreferrer"
									class="font-medium text-primary-500 hover:text-primary-600"
								>
									Open in new tab
								</a>
							</div>
						</div>
					</div>
				{/if}
			</div>
		</div>

		<!-- Description -->
		{#if event.description}
			<div class="mb-6 card-padded">
				<h3 class="mb-4 text-sm font-medium text-theme-muted">Description</h3>
				<p class="whitespace-pre-wrap text-theme">{event.description}</p>
			</div>
		{/if}

		<!-- Attendees -->
		{#if event.attendees && event.attendees.length > 0}
			<div class="mb-6 card-padded">
				<h3 class="mb-4 text-sm font-medium text-theme-muted">
					Attendees ({event.attendees.length})
				</h3>
				<div class="space-y-3">
					{#each event.attendees as attendee (attendee.email)}
						<div
							class="flex items-center gap-3 rounded-lg border border-theme bg-theme-secondary p-3"
						>
							<div
								class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-accent7-500/20"
							>
								<svg
									class="h-5 w-5 text-accent7-600 dark:text-accent7-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
									/>
								</svg>
							</div>
							<div class="min-w-0 flex-1">
								{#if attendee.displayName}
									<p class="truncate font-medium text-theme">{attendee.displayName}</p>
									<p class="truncate text-sm text-theme-muted">{attendee.email}</p>
								{:else}
									<p class="truncate font-medium text-theme">{attendee.email}</p>
								{/if}
							</div>
							{#if attendee.optional}
								<span
									class="flex-shrink-0 rounded-full bg-gray-500/10 px-2 py-0.5 text-xs font-medium text-gray-600 dark:text-gray-400"
								>
									Optional
								</span>
							{/if}
						</div>
					{/each}
				</div>
			</div>
		{/if}

		<!-- Reminders -->
		{#if event.reminders}
			<div class="mb-6 card-padded">
				<h3 class="mb-4 text-sm font-medium text-theme-muted">Reminders</h3>
				{#if event.reminders.useDefault}
					<div
						class="flex items-center gap-3 rounded-lg border border-theme bg-theme-secondary p-3"
					>
						<div
							class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-accent7-500/20"
						>
							<svg
								class="h-5 w-5 text-accent7-600 dark:text-accent7-400"
								style="fill: none"
								stroke="currentColor"
								viewBox="0 0 24 24"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
								/>
							</svg>
						</div>
						<div>
							<p class="font-medium text-theme">Default reminders</p>
							<p class="text-sm text-theme-muted">Using calendar's default reminder settings</p>
						</div>
					</div>
				{:else if event.reminders.overrides && event.reminders.overrides.length > 0}
					<div class="space-y-3">
						{#each event.reminders.overrides as reminder, index (index)}
							{@const methodLabel = reminder.method === 'email' ? 'Email' : 'Popup'}
							{@const timeLabel = formatReminderTime(reminder.minutes)}
							<div
								class="flex items-center gap-3 rounded-lg border border-theme bg-theme-secondary p-3"
							>
								<div
									class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-accent7-500/20"
								>
									{#if reminder.method === 'email'}
										<svg
											class="h-5 w-5 text-accent7-600 dark:text-accent7-400"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
											/>
										</svg>
									{:else}
										<svg
											class="h-5 w-5 text-accent7-600 dark:text-accent7-400"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
											/>
										</svg>
									{/if}
								</div>
								<div>
									<p class="font-medium text-theme">{methodLabel} notification</p>
									<p class="text-sm text-theme-muted">{timeLabel} before event</p>
								</div>
							</div>
						{/each}
					</div>
				{:else}
					<p class="text-sm text-theme-muted italic">No reminders configured for this event.</p>
				{/if}
			</div>
		{/if}

		<!-- Metadata -->
		<div class="mb-6 card-padded">
			<h3 class="mb-4 text-sm font-medium text-theme-muted">Metadata</h3>
			<div class="space-y-2 text-sm">
				<div class="flex items-center justify-between">
					<span class="text-theme-muted">Event ID</span>
					<span class="font-mono text-theme-secondary">{event.id}</span>
				</div>
				{#if event.created}
					<div class="flex items-center justify-between">
						<span class="text-theme-muted">Created</span>
						<span class="text-theme-secondary">
							{new Date(event.created).toLocaleString()}
						</span>
					</div>
				{/if}
				{#if event.updated}
					<div class="flex items-center justify-between">
						<span class="text-theme-muted">Last Updated</span>
						<span class="text-theme-secondary">
							{new Date(event.updated).toLocaleString()}
						</span>
					</div>
				{/if}
			</div>
		</div>

		<!-- Danger Zone -->
		<div
			class="rounded-lg border border-red-200 bg-red-50 p-6 dark:border-red-800 dark:bg-red-900/20"
		>
			<h2 class="mb-2 text-lg font-semibold text-red-700 dark:text-red-400">Danger Zone</h2>
			<p class="mb-4 text-sm text-red-600 dark:text-red-300">
				Deleting this event will remove it from Google Calendar. This action cannot be undone.
			</p>
			<button
				onclick={() => (showDeleteModal = true)}
				class="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700"
			>
				Delete Event
			</button>
		</div>
	</ContentContainer>
</div>

<DeleteConfirmModal
	bind:open={showDeleteModal}
	title="Delete Event"
	message="Are you sure you want to delete '{event.summary}'? This will remove it from Google Calendar and cannot be undone."
	onconfirm={handleDelete}
	oncancel={() => {}}
	loading={isDeleting}
/>
