<script lang="ts">
	import { Bell, Calendar, CreditCard, Users, Megaphone, Settings, Check, ChevronDown, ChevronUp, ExternalLink } from 'lucide-svelte';
	import { goto } from '$app/navigation';
	import { onMount } from 'svelte';

	interface Notification {
		id: string;
		type: 'welcome' | 'event' | 'payment' | 'membership' | 'system' | 'announcement';
		title: string;
		message: string;
		link: string | null;
		read_at: string | null;
		created_at: string;
	}

	let { data } = $props();
	let notifications = $state<Notification[]>(data.notifications);
	let filter = $state<'all' | 'unread'>('all');
	let expandedId = $state<string | null>(data.expandedId);

	// Auto-expand and scroll to notification if ID is in URL
	onMount(() => {
		if (data.expandedId) {
			const notification = notifications.find(n => n.id === data.expandedId);
			if (notification && !notification.read_at) {
				markAsRead(notification.id);
			}
			// Scroll to the notification
			setTimeout(() => {
				const element = document.getElementById(`notification-${data.expandedId}`);
				if (element) {
					element.scrollIntoView({ behavior: 'smooth', block: 'center' });
				}
			}, 100);
		}
	});

	function toggleExpand(id: string) {
		if (expandedId === id) {
			expandedId = null;
		} else {
			expandedId = id;
			const notification = notifications.find(n => n.id === id);
			if (notification && !notification.read_at) {
				markAsRead(id);
			}
		}
	}

	const filteredNotifications = $derived(
		filter === 'unread'
			? notifications.filter(n => !n.read_at)
			: notifications
	);

	const unreadCount = $derived(notifications.filter(n => !n.read_at).length);

	function getTypeIcon(type: Notification['type']) {
		switch (type) {
			case 'welcome': return Users;
			case 'event': return Calendar;
			case 'payment': return CreditCard;
			case 'membership': return Users;
			case 'system': return Settings;
			case 'announcement': return Megaphone;
			default: return Bell;
		}
	}

	function getTypeColor(type: Notification['type']) {
		switch (type) {
			case 'welcome': return 'text-green-600 bg-green-100';
			case 'event': return 'text-blue-600 bg-blue-100';
			case 'payment': return 'text-amber-600 bg-amber-100';
			case 'membership': return 'text-purple-600 bg-purple-100';
			case 'system': return 'text-slate-600 bg-slate-100';
			case 'announcement': return 'text-monaco-600 bg-monaco-100';
			default: return 'text-slate-600 bg-slate-100';
		}
	}

	function getTypeBadge(type: Notification['type']) {
		switch (type) {
			case 'welcome': return { text: 'Welcome', class: 'bg-green-100 text-green-700' };
			case 'event': return { text: 'Event', class: 'bg-blue-100 text-blue-700' };
			case 'payment': return { text: 'Payment', class: 'bg-amber-100 text-amber-700' };
			case 'membership': return { text: 'Membership', class: 'bg-purple-100 text-purple-700' };
			case 'system': return { text: 'System', class: 'bg-slate-100 text-slate-700' };
			case 'announcement': return { text: 'Announcement', class: 'bg-monaco-100 text-monaco-700' };
			default: return { text: 'Other', class: 'bg-slate-100 text-slate-700' };
		}
	}

	function formatDate(dateString: string) {
		const date = new Date(dateString);
		const now = new Date();
		const diffMs = now.getTime() - date.getTime();
		const diffMins = Math.floor(diffMs / 60000);
		const diffHours = Math.floor(diffMs / 3600000);
		const diffDays = Math.floor(diffMs / 86400000);

		if (diffMins < 1) return 'Just now';
		if (diffMins < 60) return `${diffMins} minute${diffMins === 1 ? '' : 's'} ago`;
		if (diffHours < 24) return `${diffHours} hour${diffHours === 1 ? '' : 's'} ago`;
		if (diffDays < 7) return `${diffDays} day${diffDays === 1 ? '' : 's'} ago`;

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

	async function markAsRead(id: string) {
		try {
			const response = await fetch(`/api/notifications/${id}/read`, { method: 'POST' });
			if (response.ok) {
				notifications = notifications.map(n =>
					n.id === id ? { ...n, read_at: new Date().toISOString() } : n
				);
			}
		} catch (e) {
			console.error('Failed to mark as read:', e);
		}
	}

	async function markAllAsRead() {
		try {
			const response = await fetch('/api/notifications/read-all', { method: 'POST' });
			if (response.ok) {
				const now = new Date().toISOString();
				notifications = notifications.map(n => ({ ...n, read_at: n.read_at || now }));
			}
		} catch (e) {
			console.error('Failed to mark all as read:', e);
		}
	}

</script>

<svelte:head>
	<title>Notifications | Monaco USA</title>
</svelte:head>

<div class="max-w-4xl mx-auto">
	<!-- Header -->
	<div class="mb-8">
		<div class="flex items-center justify-between">
			<div>
				<h1 class="text-2xl font-bold text-slate-900">Notifications</h1>
				<p class="mt-1 text-slate-600">
					{#if unreadCount > 0}
						You have {unreadCount} unread notification{unreadCount === 1 ? '' : 's'}
					{:else}
						All caught up!
					{/if}
				</p>
			</div>
			{#if unreadCount > 0}
				<button
					onclick={markAllAsRead}
					class="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
				>
					<Check class="h-4 w-4" />
					Mark all as read
				</button>
			{/if}
		</div>

		<!-- Filter tabs -->
		<div class="mt-6 flex gap-2">
			<button
				onclick={() => filter = 'all'}
				class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {filter === 'all' ? 'bg-monaco-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'}"
			>
				All ({notifications.length})
			</button>
			<button
				onclick={() => filter = 'unread'}
				class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {filter === 'unread' ? 'bg-monaco-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'}"
			>
				Unread ({unreadCount})
			</button>
		</div>
	</div>

	<!-- Notifications List -->
	{#if filteredNotifications.length === 0}
		<div class="rounded-xl border border-slate-200 bg-white p-12 text-center">
			<Bell class="mx-auto h-12 w-12 text-slate-300" />
			<h3 class="mt-4 text-lg font-medium text-slate-900">
				{filter === 'unread' ? 'No unread notifications' : 'No notifications yet'}
			</h3>
			<p class="mt-2 text-slate-600">
				{filter === 'unread' ? 'You\'re all caught up!' : 'When you receive notifications, they\'ll appear here.'}
			</p>
		</div>
	{:else}
		<div class="space-y-3">
			{#each filteredNotifications as notification}
				{@const Icon = getTypeIcon(notification.type)}
				{@const badge = getTypeBadge(notification.type)}
				{@const isExpanded = expandedId === notification.id}
				<div
					id="notification-{notification.id}"
					class="rounded-xl border bg-white transition-all {notification.read_at ? 'border-slate-200' : 'border-monaco-200 bg-monaco-50/30'} {isExpanded ? 'shadow-lg ring-2 ring-monaco-500/20' : 'hover:shadow-md'}"
				>
					<button
						onclick={() => toggleExpand(notification.id)}
						class="w-full p-4 text-left"
					>
						<div class="flex items-start gap-4">
							<div class="flex-shrink-0 rounded-full p-3 {getTypeColor(notification.type)}">
								<Icon class="h-5 w-5" />
							</div>
							<div class="min-w-0 flex-1">
								<div class="flex items-start justify-between gap-4">
									<div class="min-w-0 flex-1">
										<div class="flex items-center gap-2 mb-1">
											<span class="rounded-full px-2 py-0.5 text-xs font-medium {badge.class}">
												{badge.text}
											</span>
											{#if !notification.read_at}
												<span class="h-2 w-2 rounded-full bg-monaco-600"></span>
											{/if}
										</div>
										<h3 class="text-base font-semibold text-slate-900">
											{notification.title}
										</h3>
										{#if !isExpanded}
											<p class="mt-1 text-sm text-slate-600 line-clamp-2">
												{notification.message}
											</p>
										{/if}
										<p class="mt-2 text-xs text-slate-400">
											{formatDate(notification.created_at)}
										</p>
									</div>
									<div class="flex-shrink-0 text-slate-400">
										{#if isExpanded}
											<ChevronUp class="h-5 w-5" />
										{:else}
											<ChevronDown class="h-5 w-5" />
										{/if}
									</div>
								</div>
							</div>
						</div>
					</button>

					<!-- Expanded content -->
					{#if isExpanded}
						<div class="border-t border-slate-100 px-4 pb-4 pt-3 ml-16">
							<div class="prose prose-sm prose-slate max-w-none">
								<p class="text-slate-700 whitespace-pre-wrap">{notification.message}</p>
							</div>
							{#if notification.link}
								<div class="mt-4">
									<a
										href={notification.link}
										class="inline-flex items-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 transition-colors"
									>
										<ExternalLink class="h-4 w-4" />
										View Details
									</a>
								</div>
							{/if}
						</div>
					{/if}
				</div>
			{/each}
		</div>
	{/if}
</div>
