<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 {
		getConversationTypeLabel,
		getParticipantNames,
		getLastMessagePreview,
		getEntityDisplay,
		deleteConversation,
		archiveConversation
	} from '$lib/utils/messages';
	import { unreadCounts } from '$lib/stores/unreadCounts.svelte';

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

	let conversations = $derived(
		data.conversations.data?.getMyConversations?.edges?.map((e) => e?.node).filter(Boolean) ?? []
	);
	let currentTab = $derived(page.url.searchParams.get('tab') ?? 'all');

	// Lookups from parent layout
	let accountLookup = $derived(data.accountLookup);
	let customerLookup = $derived(data.customerLookup);

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

	// Filter for unread tab (client-side)
	let filteredConversations = $derived(
		currentTab === 'unread' ? conversations.filter((c) => c && c.unreadCount > 0) : conversations
	);

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

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

		try {
			await deleteConversation(id);
			unreadCounts.fetchCounts();
			await invalidateAll();
		} catch (error) {
			console.error('Failed to delete conversation:', error);
		}
	}

	async function handleArchive(id: string, isArchived: boolean, event: MouseEvent) {
		event.stopPropagation();
		event.preventDefault();

		try {
			await archiveConversation(id, !isArchived);
			await invalidateAll();
		} catch (error) {
			console.error('Failed to archive conversation:', error);
		}
	}

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

	function getTypeBadgeClass(type: string | null | undefined): string {
		switch (type) {
			case 'DIRECT':
				return 'bg-primary-100 text-primary-700 dark:bg-primary-900/30 dark:text-primary-300';
			case 'GROUP':
				return 'bg-secondary-100 text-secondary-700 dark:bg-secondary-900/30 dark:text-secondary-300';
			case 'SUPPORT':
				return 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-300';
			default:
				return 'bg-black/5 text-theme-secondary dark:bg-white/10';
		}
	}
</script>

<svelte:head>
	<title>Messages | 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">Messages</h1>
		</div>

		<a
			href="/messages/new"
			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"
		>
			<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="M12 4v16m8-8H4" />
			</svg>
			New
		</a>
	</div>

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

	<!-- Conversations List -->
	{#if filteredConversations.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="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>
			<p class="mb-4 text-theme-secondary">
				{#if currentTab === 'unread'}
					No unread messages
				{:else if currentTab === 'archived'}
					No archived conversations
				{:else}
					No conversations yet
				{/if}
			</p>
			{#if currentTab !== 'archived'}
				<a
					href="/messages/new"
					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"
				>
					Start a Conversation
				</a>
			{/if}
		</div>
	{:else}
		<div class="space-y-3">
			{#each filteredConversations as conversation (conversation?.id)}
				{@const entityDisplay = getEntityDisplay(conversation?.entity, {
					accountLookup,
					customerLookup
				})}
				<a href="/messages/{conversation?.id}" class="group block card-message">
					<div class="flex items-start gap-3">
						<!-- Unread indicator -->
						<div class="mt-1.5 flex-shrink-0">
							{#if conversation && conversation.unreadCount > 0}
								<span
									class="flex h-5 min-w-5 items-center justify-center rounded-full bg-message-500 px-1 text-xs font-semibold text-white"
								>
									{conversation.unreadCount > 99 ? '99+' : conversation.unreadCount}
								</span>
							{:else}
								<span class="block h-5 w-5"></span>
							{/if}
						</div>

						<div class="min-w-0 flex-1">
							<!-- Top row: type badge and time -->
							<div class="mb-1 flex items-center justify-between gap-2">
								<span
									class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium {getTypeBadgeClass(
										conversation?.conversationType
									)}"
								>
									{getConversationTypeLabel(conversation?.conversationType)}
								</span>
								<span class="flex-shrink-0 text-xs text-theme-muted">
									{formatTime(conversation?.lastMessageAt)}
								</span>
							</div>

							<!-- Entity info (if present) -->
							{#if entityDisplay}
								<p class="mb-1 text-xs text-theme-secondary">
									{entityDisplay.type}: {entityDisplay.name}
								</p>
							{/if}

							<!-- Subject -->
							<h3
								class="mb-1 font-medium text-theme {conversation && conversation.unreadCount > 0
									? 'font-semibold'
									: ''}"
							>
								{conversation?.subject || 'No subject'}
							</h3>

							<!-- Last message preview -->
							<p class="mb-2 line-clamp-1 text-sm text-theme-secondary">
								{getLastMessagePreview(conversation?.messages, 80)}
							</p>

							<!-- Participants -->
							<p class="text-xs text-theme-muted">
								{getParticipantNames(conversation?.participants, undefined, 3)}
							</p>
						</div>

						<!-- Archive button -->
						<button
							onclick={(e) => handleArchive(conversation.id, conversation.isArchived, e)}
							class="flex-shrink-0 rounded-lg p-1.5 text-theme-muted transition-all hover:bg-black/10 hover:text-theme-secondary dark:hover:bg-white/10"
							aria-label={conversation?.isArchived
								? 'Unarchive conversation'
								: 'Archive conversation'}
						>
							<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="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4"
								/>
							</svg>
						</button>

						<!-- Delete button (only if canDelete) -->
						{#if conversation?.canDelete}
							<button
								onclick={(e) => handleDelete(conversation.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 conversation"
							>
								<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>
						{/if}
					</div>
				</a>
			{/each}
		</div>
	{/if}
</div>

<!-- Mobile FAB -->
<a
	href="/messages/new"
	class="fixed right-4 bottom-20 z-30 flex h-14 w-14 items-center justify-center rounded-full bg-primary-600 text-white shadow-lg transition-transform hover:scale-105 hover:bg-primary-700 sm:hidden"
	aria-label="New conversation"
>
	<svg class="h-6 w-6" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
		<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
	</svg>
</a>
