<script lang="ts">
	import type { PageData } from './$types';
	import { goto } from '$app/navigation';
	import { formatDistanceToNow, format } from 'date-fns';
	import {
		markAsRead,
		deleteNotification,
		getEventTypeLabel,
		getActionUrl,
		getEntityTypeLabel
	} from '$lib/utils/notifications';
	import { unreadCounts } from '$lib/stores/unreadCounts.svelte';

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

	let notification = $derived(data.notification.data?.notification);

	// Mark as read on mount
	$effect(() => {
		if (notification && !notification.isRead) {
			markAsRead(notification.id)
				.then(() => {
					unreadCounts.decrementNotifications();
				})
				.catch(console.error);
		}
	});

	async function handleDelete() {
		if (!notification) return;
		if (!confirm('Are you sure you want to delete this notification?')) return;

		try {
			await deleteNotification(notification.id);
			unreadCounts.fetchCounts();
			goto('/notifications');
		} catch (error) {
			console.error('Failed to delete notification:', error);
		}
	}

	function formatTime(dateString: string | null | undefined): string {
		if (!dateString) return '';
		try {
			return formatDistanceToNow(new Date(dateString), { addSuffix: true });
		} catch {
			return '';
		}
	}

	function formatDateTime(dateString: string | null | undefined): string {
		if (!dateString) return '';
		try {
			return format(new Date(dateString), 'PPpp');
		} catch {
			return '';
		}
	}

	function goBack() {
		goto('/notifications');
	}

	let actionUrl = $derived(notification ? getActionUrl(notification) : null);
</script>

<svelte:head>
	<title>{notification?.subject ?? 'Notification'} | Nexus</title>
</svelte:head>

<div class="mx-auto max-w-3xl px-4 py-6">
	<!-- Header -->
	<div class="mb-6 flex items-center justify-between">
		<div class="flex items-center gap-3">
			<button onclick={goBack} class="rounded-lg interactive p-2" aria-label="Go back">
				<svg
					class="h-5 w-5 text-theme-secondary"
					style="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>
			</button>
			<h1 class="text-xl font-semibold text-theme">Notification</h1>
		</div>

		<button
			onclick={handleDelete}
			class="rounded-lg p-2 text-error-600 transition-colors hover:bg-error-50 dark:text-error-400 dark:hover:bg-error-900/20"
			aria-label="Delete notification"
		>
			<svg class="h-5 w-5" style="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>
		</button>
	</div>

	{#if !notification}
		<div class="rounded-xl border border-theme bg-theme-card p-8 text-center">
			<p class="text-theme-secondary">Notification not found</p>
		</div>
	{:else}
		<div class="space-y-4">
			<!-- Main notification card -->
			<div class="rounded-xl border border-theme bg-theme-card p-6">
				<!-- Subject -->
				<h2 class="mb-2 text-lg font-semibold text-theme">{notification.subject}</h2>

				<!-- Time -->
				<p class="mb-4 text-sm text-theme-muted">
					{formatTime(notification.createdAt)}
					<span class="mx-1">·</span>
					{formatDateTime(notification.createdAt)}
				</p>

				<!-- Body -->
				{#if notification.body}
					<div class="prose prose-sm max-w-none text-theme-secondary dark:prose-invert">
						<p class="whitespace-pre-wrap">{notification.body}</p>
					</div>
				{/if}

				<!-- Action button -->
				{#if actionUrl}
					<div class="mt-6">
						<a
							href={actionUrl}
							class="inline-flex items-center gap-2 rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-700"
						>
							View Related Item
							<svg class="h-4 w-4" style="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>
						</a>
					</div>
				{/if}
			</div>

			<!-- Event details -->
			{#if notification.event}
				<div class="rounded-xl border border-theme bg-theme-card p-6">
					<h3 class="mb-4 text-sm font-semibold tracking-wide text-theme-muted uppercase">
						Event Details
					</h3>

					<dl class="grid grid-cols-1 gap-4 sm:grid-cols-2">
						{#if notification.event.eventType}
							<div>
								<dt class="text-xs font-medium text-theme-muted">Event Type</dt>
								<dd class="mt-1 text-sm text-theme">
									{getEventTypeLabel(notification.event.eventType)}
								</dd>
							</div>
						{/if}

						{#if notification.event.entityType}
							<div>
								<dt class="text-xs font-medium text-theme-muted">Entity Type</dt>
								<dd class="mt-1 text-sm text-theme">
									{getEntityTypeLabel(notification.event.entityType)}
								</dd>
							</div>
						{/if}

						{#if notification.event.entityId}
							<div>
								<dt class="text-xs font-medium text-theme-muted">Entity ID</dt>
								<dd class="mt-1 font-mono text-xs text-theme-secondary">
									{notification.event.entityId}
								</dd>
							</div>
						{/if}

						{#if notification.event.createdAt}
							<div>
								<dt class="text-xs font-medium text-theme-muted">Event Time</dt>
								<dd class="mt-1 text-sm text-theme">
									{formatDateTime(notification.event.createdAt)}
								</dd>
							</div>
						{/if}
					</dl>
				</div>
			{/if}

			<!-- Rule info -->
			{#if notification.rule}
				<div class="rounded-xl border border-theme bg-theme-card p-6">
					<h3 class="mb-4 text-sm font-semibold tracking-wide text-theme-muted uppercase">
						Notification Rule
					</h3>

					<dl class="space-y-3">
						<div>
							<dt class="text-xs font-medium text-theme-muted">Rule Name</dt>
							<dd class="mt-1 text-sm text-theme">{notification.rule.name}</dd>
						</div>

						{#if notification.rule.description}
							<div>
								<dt class="text-xs font-medium text-theme-muted">Description</dt>
								<dd class="mt-1 text-sm text-theme-secondary">{notification.rule.description}</dd>
							</div>
						{/if}
					</dl>
				</div>
			{/if}

			<!-- Metadata (if present) -->
			{#if notification.metadata && Object.keys(notification.metadata).length > 0}
				<div class="rounded-xl border border-theme bg-theme-card p-6">
					<h3 class="mb-4 text-sm font-semibold tracking-wide text-theme-muted uppercase">
						Additional Data
					</h3>
					<pre
						class="overflow-x-auto rounded-lg bg-black/5 p-4 text-xs text-theme-secondary dark:bg-white/5">{JSON.stringify(
							notification.metadata,
							null,
							2
						)}</pre>
				</div>
			{/if}
		</div>
	{/if}
</div>
