<script lang="ts">
	import type { PageData } from './$types';
	import { page } from '$app/state';
	import { invalidateAll } from '$app/navigation';
	import { formatDistanceToNow } from 'date-fns';
	import TabFilter from '$lib/components/shared/TabFilter.svelte';
	import {
		markAllAsRead,
		deleteNotification,
		getEventTypeLabel,
		getBodyPreview
	} from '$lib/utils/notifications';
	import { unreadCounts } from '$lib/stores/unreadCounts.svelte';

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

	let notifications = $derived(data.notifications.data?.myNotifications ?? []);
	let currentTab = $derived(page.url.searchParams.get('tab') ?? 'all');
	let isLoading = $state(false);

	// Determine dashboard URL based on user type
	let dashboardUrl = $derived(
		data.user?.data?.me?.__typename === 'CustomerProfileType' ? '/customer' : '/team'
	);

	const tabs = [
		{ id: 'all', label: 'All' },
		{ id: 'unread', label: 'Unread', count: unreadCounts.notificationCount }
	];

	async function handleMarkAllRead() {
		if (isLoading) return;
		isLoading = true;
		try {
			await markAllAsRead();
			unreadCounts.fetchCounts();
			await invalidateAll();
		} catch (error) {
			console.error('Failed to mark all as read:', error);
		} finally {
			isLoading = false;
		}
	}

	async function handleDelete(id: string, event: MouseEvent) {
		event.stopPropagation();
		event.preventDefault();
		if (!confirm('Are you sure you want to delete this notification?')) return;

		try {
			await deleteNotification(id);
			unreadCounts.fetchCounts();
			await invalidateAll();
		} 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 '';
		}
	}
</script>

<svelte:head>
	<title>Notifications | 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">
			<a href={dashboardUrl} class="rounded-lg interactive p-2" aria-label="Go to dashboard">
				<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>
			</a>
			<h1 class="text-xl font-semibold text-theme">Notifications</h1>
		</div>

		{#if notifications.length > 0 && unreadCounts.notificationCount > 0}
			<button
				onclick={handleMarkAllRead}
				disabled={isLoading}
				class="rounded-lg px-3 py-1.5 text-sm font-medium text-primary-600 transition-colors hover:bg-primary-50 disabled:opacity-50 dark:text-primary-400 dark:hover:bg-primary-900/20"
			>
				Mark all read
			</button>
		{/if}
	</div>

	<!-- Tabs -->
	<div class="mb-6">
		<TabFilter {tabs} />
	</div>

	<!-- Notifications List -->
	{#if notifications.length === 0}
		<div class="rounded-xl border border-theme bg-theme-card p-8 text-center">
			<svg
				class="mx-auto mb-4 h-12 w-12 text-theme-muted"
				style="fill: none"
				stroke="currentColor"
				viewBox="0 0 24 24"
			>
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					stroke-width="1.5"
					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>
			<p class="text-theme-secondary">
				{#if currentTab === 'unread'}
					No unread notifications
				{:else}
					No notifications yet
				{/if}
			</p>
		</div>
	{:else}
		<div class="space-y-3">
			{#each notifications as notification (notification.id)}
				<a href="/notifications/{notification.id}" class="group block card-notification">
					<div class="flex items-start gap-3">
						<!-- Unread indicator -->
						<div class="mt-1.5 flex-shrink-0">
							{#if !notification.isRead}
								<span class="block h-2.5 w-2.5 rounded-full bg-notification-500"></span>
							{:else}
								<span class="block h-2.5 w-2.5 rounded-full bg-transparent"></span>
							{/if}
						</div>

						<div class="min-w-0 flex-1">
							<!-- Subject and time -->
							<div class="mb-1 flex items-start justify-between gap-2">
								<h3 class="font-medium text-theme {notification.isRead ? '' : 'font-semibold'}">
									{notification.subject}
								</h3>
								<span class="flex-shrink-0 text-xs text-theme-muted">
									{formatTime(notification.createdAt)}
								</span>
							</div>

							<!-- Body preview -->
							{#if notification.body}
								<p class="mb-2 line-clamp-2 text-sm text-theme-secondary">
									{getBodyPreview(notification.body, 120)}
								</p>
							{/if}

							<!-- Event type badge -->
							<div class="flex items-center gap-2">
								{#if notification.event?.eventType}
									<span
										class="inline-flex items-center rounded-full bg-black/5 px-2 py-0.5 text-xs font-medium text-theme-secondary dark:bg-white/10"
									>
										{getEventTypeLabel(notification.event.eventType)}
									</span>
								{/if}
								{#if notification.event?.entityType}
									<span
										class="inline-flex items-center rounded-full bg-primary-100 px-2 py-0.5 text-xs font-medium text-primary-700 dark:bg-primary-900/30 dark:text-primary-300"
									>
										{notification.event.entityType}
									</span>
								{/if}
							</div>
						</div>

						<!-- Delete button -->
						<button
							onclick={(e) => handleDelete(notification.id, e)}
							class="flex-shrink-0 rounded-lg p-1.5 text-theme-muted transition-all hover:bg-error-100 hover:text-error-600 dark:hover:bg-error-900/30 dark:hover:text-error-400"
							aria-label="Delete notification"
						>
							<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="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>
				</a>
			{/each}
		</div>
	{/if}
</div>
