<script lang="ts">
	import { goto } from '$app/navigation';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import type { Conversation } from '$lib/graphql/queries/messaging';
	import { unreadCounts } from '$lib/stores/unreadCounts.svelte';

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

	let conversations = $derived(data.conversations as Conversation[]);

	function formatRelativeTime(dateStr: string | null): string {
		if (!dateStr) return 'No messages';
		const date = new Date(dateStr);
		const now = new Date();
		const diffMs = now.getTime() - date.getTime();
		const diffSecs = Math.floor(diffMs / 1000);
		const diffMins = Math.floor(diffSecs / 60);
		const diffHours = Math.floor(diffMins / 60);
		const diffDays = Math.floor(diffHours / 24);

		if (diffSecs < 60) return 'Just now';
		if (diffMins < 60) return `${diffMins}m ago`;
		if (diffHours < 24) return `${diffHours}h ago`;
		if (diffDays < 7) return `${diffDays}d ago`;
		return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
	}

	function getConversationTitle(conversation: Conversation): string {
		if (conversation.subject) return conversation.subject;

		// Build title from participants
		const participants = conversation.participants
			.filter((p) => p.participantProfile)
			.map((p) => p.participantProfile?.fullName)
			.filter(Boolean)
			.slice(0, 3);

		if (participants.length === 0) return 'Conversation';
		if (participants.length <= 2) return participants.join(', ');
		return `${participants.slice(0, 2).join(', ')} +${conversation.participants.length - 2}`;
	}

	function getConversationTypeLabel(type: string): string {
		switch (type) {
			case 'DIRECT':
				return 'Direct';
			case 'GROUP':
				return 'Group';
			case 'SUPPORT':
				return 'Support';
			default:
				return type;
		}
	}

	function getConversationTypeClass(type: string): string {
		switch (type) {
			case 'DIRECT':
				return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
			case 'GROUP':
				return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400';
			case 'SUPPORT':
				return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
		}
	}
</script>

<svelte:head>
	<title>Messages - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
			<div>
				<h1 class="text-2xl font-bold text-accent6-600 md:text-3xl dark:text-accent6-400">
					Messages
				</h1>
				<p class="mt-1 text-theme-secondary">
					{conversations.length} conversation{conversations.length !== 1 ? 's' : ''}
					{#if unreadCounts.messageCount > 0}
						<span class="text-accent-600 dark:text-accent-400">
							({unreadCounts.messageCount} unread)
						</span>
					{/if}
				</p>
			</div>
			<a href="/messages/new" class="btn-primary flex items-center justify-center gap-2 sm:w-auto">
				<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="M12 4v16m8-8H4"
					/>
				</svg>
				New Message
			</a>
		</div>

		<!-- Conversations List -->
		{#if conversations.length > 0}
			<div class="space-y-3">
				{#each conversations as conversation (conversation.id)}
					<a
						href="/messages/{conversation.id}"
						class="group hover:bg-theme-hover flex items-start gap-4 rounded-lg border border-theme bg-theme-card p-4 transition-colors {conversation.unreadCount >
						0
							? 'border-l-4 border-l-accent-500'
							: ''}"
					>
						<!-- Avatar placeholder -->
						<div
							class="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-accent-100 text-lg font-semibold text-accent-600 dark:bg-accent-900/30 dark:text-accent-400"
						>
							{#if conversation.conversationType === 'GROUP'}
								<svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
									/>
								</svg>
							{:else}
								{getConversationTitle(conversation).charAt(0).toUpperCase()}
							{/if}
						</div>

						<div class="min-w-0 flex-1">
							<div class="flex items-start justify-between gap-2">
								<div class="min-w-0 flex-1">
									<!-- Title -->
									<h3
										class="truncate font-semibold {conversation.unreadCount > 0
											? 'text-theme'
											: 'text-theme-secondary'}"
									>
										{getConversationTitle(conversation)}
									</h3>

									<!-- Participants preview -->
									<p class="mt-1 truncate text-sm text-theme-muted">
										{conversation.participants.length} participant{conversation.participants
											.length !== 1
											? 's'
											: ''}
									</p>
								</div>

								<!-- Meta -->
								<div class="flex shrink-0 flex-col items-end gap-1">
									<span class="text-xs text-theme-muted">
										{formatRelativeTime(conversation.lastMessageAt)}
									</span>
									{#if conversation.unreadCount > 0}
										<span
											class="rounded-full bg-accent-500 px-2 py-0.5 text-xs font-semibold text-white"
										>
											{conversation.unreadCount > 99 ? '99+' : conversation.unreadCount}
										</span>
									{/if}
								</div>
							</div>

							<!-- Type badge -->
							<div class="mt-2 flex items-center gap-2">
								<span
									class="rounded px-2 py-0.5 text-xs font-medium {getConversationTypeClass(
										conversation.conversationType
									)}"
								>
									{getConversationTypeLabel(conversation.conversationType)}
								</span>
								{#if conversation.entityType}
									<span class="text-xs text-theme-muted">
										{conversation.entityType}
									</span>
								{/if}
								{#if conversation.isArchived}
									<span class="text-xs text-theme-muted italic">Archived</span>
								{/if}
							</div>
						</div>
					</a>
				{/each}
			</div>
		{:else}
			<!-- Empty state -->
			<div class="rounded-lg border border-dashed border-theme py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
					/>
				</svg>
				<h3 class="mt-4 text-lg font-medium text-theme">No conversations yet</h3>
				<p class="mt-2 text-theme-secondary">
					Start a conversation with a team member or customer.
				</p>
				<a href="/messages/new" class="mt-4 btn-primary inline-block"> New Message </a>
			</div>
		{/if}
	</ContentContainer>
</div>
