<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { client } from '$lib/graphql/client';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import type { Conversation, Message } from '$lib/graphql/queries/messaging';
	import {
		SEND_MESSAGE,
		MARK_CONVERSATION_AS_READ,
		ARCHIVE_CONVERSATION,
		LEAVE_CONVERSATION,
		type SendMessageResult,
		type SendMessageInput
	} from '$lib/graphql/mutations/messaging';
	import { unreadCounts } from '$lib/stores/unreadCounts.svelte';

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

	let conversation = $derived(data.conversation as Conversation);
	let messagesOverride = $state<Message[] | null>(null);
	let messages = $derived(messagesOverride ?? conversation.messages ?? []);

	// New message state
	let newMessage = $state('');
	let isSending = $state(false);
	let messagesContainer: HTMLDivElement | undefined = $state();

	function formatTime(dateStr: string): string {
		const date = new Date(dateStr);
		const now = new Date();
		const isToday = date.toDateString() === now.toDateString();

		if (isToday) {
			return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
		}
		return date.toLocaleDateString('en-US', {
			month: 'short',
			day: 'numeric',
			hour: 'numeric',
			minute: '2-digit'
		});
	}

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

		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}`;
	}

	async function handleSendMessage() {
		if (!newMessage.trim() || isSending) return;

		isSending = true;

		try {
			const input: SendMessageInput = {
				conversationId: conversation.id,
				content: newMessage.trim()
			};

			const result = await client.mutate<SendMessageResult>({
				mutation: SEND_MESSAGE,
				variables: { input }
			});

			if (result.data?.sendMessage) {
				// Add message to list (prepend since messages are sorted DESC)
				messagesOverride = [result.data.sendMessage, ...messages];
				newMessage = '';

				// Scroll to bottom
				setTimeout(() => {
					if (messagesContainer) {
						messagesContainer.scrollTop = 0;
					}
				}, 100);
			}
		} catch (err) {
			console.error('Failed to send message:', err);
		} finally {
			isSending = false;
		}
	}

	async function handleArchive() {
		try {
			await client.mutate({
				mutation: ARCHIVE_CONVERSATION,
				variables: { id: conversation.id, isArchived: !conversation.isArchived }
			});
			goto('/messages');
		} catch (err) {
			console.error('Failed to archive conversation:', err);
		}
	}

	async function handleLeave() {
		if (!confirm('Are you sure you want to leave this conversation?')) return;

		try {
			await client.mutate({
				mutation: LEAVE_CONVERSATION,
				variables: { conversationId: conversation.id }
			});
			goto('/messages');
		} catch (err) {
			console.error('Failed to leave conversation:', err);
		}
	}

	onMount(async () => {
		// Mark conversation as read
		if (conversation.unreadCount > 0) {
			try {
				await client.mutate({
					mutation: MARK_CONVERSATION_AS_READ,
					variables: { id: conversation.id }
				});
				unreadCounts.decrementMessages(conversation.unreadCount);
			} catch (err) {
				console.error('Failed to mark conversation as read:', err);
			}
		}
	});
</script>

<svelte:head>
	<title>{getConversationTitle()} - Messages - Nexus</title>
</svelte:head>

<div class="flex h-[calc(100vh-4rem)] flex-col">
	<!-- Header -->
	<div class="border-b border-theme bg-theme-card px-4 py-3 sm:px-6">
		<div class="mx-auto flex max-w-4xl items-center justify-between gap-4">
			<div class="flex items-center gap-4">
				<a
					href="/messages"
					class="hover:bg-theme-hover rounded p-1 text-theme-muted hover:text-theme"
					aria-label="Back to messages"
				>
					<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="M15 19l-7-7 7-7"
						/>
					</svg>
				</a>
				<div>
					<h1 class="font-semibold text-theme">{getConversationTitle()}</h1>
					<p class="text-sm text-theme-muted">
						{conversation.participants.length} participant{conversation.participants.length !== 1
							? 's'
							: ''}
					</p>
				</div>
			</div>

			<!-- Actions dropdown -->
			<div class="relative">
				<button
					type="button"
					class="hover:bg-theme-hover rounded p-2 text-theme-muted hover:text-theme"
					aria-label="Conversation options"
					onclick={(e) => {
						const menu = e.currentTarget.nextElementSibling;
						if (menu) menu.classList.toggle('hidden');
					}}
				>
					<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 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z"
						/>
					</svg>
				</button>
				<div
					class="absolute right-0 z-10 mt-2 hidden w-48 rounded-lg border border-theme bg-theme-card py-1 shadow-lg"
				>
					<button
						type="button"
						class="hover:bg-theme-hover w-full px-4 py-2 text-left text-sm text-theme"
						onclick={handleArchive}
					>
						{conversation.isArchived ? 'Unarchive' : 'Archive'}
					</button>
					<button
						type="button"
						class="hover:bg-theme-hover w-full px-4 py-2 text-left text-sm text-red-600 dark:text-red-400"
						onclick={handleLeave}
					>
						Leave conversation
					</button>
				</div>
			</div>
		</div>
	</div>

	<!-- Messages (reversed order - newest at bottom visually but top of list) -->
	<div
		bind:this={messagesContainer}
		class="flex-1 overflow-y-auto px-4 py-4 sm:px-6"
		style="display: flex; flex-direction: column-reverse;"
	>
		<div class="mx-auto w-full max-w-4xl space-y-4">
			{#each messages as message (message.id)}
				{#if message.isSystemMessage}
					<!-- System message - centered, muted style -->
					<div class="flex justify-center py-2">
						<div
							class="flex items-center gap-2 rounded-full bg-gray-100 px-4 py-1.5 text-sm text-gray-600 dark:bg-gray-800 dark:text-gray-400"
						>
							<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
								/>
							</svg>
							<span class="italic">{message.content}</span>
						</div>
					</div>
				{:else}
					<!-- Regular message -->
					<div class="flex gap-3">
						<!-- Avatar -->
						<div
							class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-accent-100 text-sm font-semibold text-accent-600 dark:bg-accent-900/30 dark:text-accent-400"
						>
							{message.authorProfile?.fullName?.charAt(0).toUpperCase() ?? '?'}
						</div>

						<div class="min-w-0 flex-1">
							<!-- Author and time -->
							<div class="flex items-baseline gap-2">
								<span class="font-medium text-theme">
									{message.authorProfile?.fullName ?? 'Unknown'}
								</span>
								<span class="text-xs text-theme-muted">
									{formatTime(message.createdAt)}
								</span>
							</div>

							<!-- Content -->
							<div class="mt-1 text-theme {message.isDeleted ? 'text-theme-muted italic' : ''}">
								{#if message.isDeleted}
									This message was deleted
								{:else}
									{message.content}
								{/if}
							</div>
						</div>
					</div>
				{/if}
			{:else}
				<div class="py-8 text-center text-theme-muted">
					No messages yet. Start the conversation!
				</div>
			{/each}
		</div>
	</div>

	<!-- Message input -->
	<div class="border-t border-theme bg-theme-card px-4 py-3 sm:px-6">
		<form
			class="mx-auto flex max-w-4xl gap-3"
			onsubmit={(e) => {
				e.preventDefault();
				handleSendMessage();
			}}
		>
			<label class="sr-only" for="message-input">Message</label>
			<input
				id="message-input"
				type="text"
				bind:value={newMessage}
				placeholder="Type a message..."
				class="flex-1 rounded-lg border border-theme bg-theme px-4 py-2 text-theme placeholder:text-theme-muted focus:border-accent-500 focus:ring-1 focus:ring-accent-500 focus:outline-none"
				disabled={isSending}
			/>
			<button
				type="submit"
				class="btn-primary flex items-center gap-2"
				disabled={!newMessage.trim() || isSending}
			>
				{#if isSending}
					<svg class="h-5 w-5 animate-spin" fill="none" viewBox="0 0 24 24">
						<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"
						></circle>
						<path
							class="opacity-75"
							fill="currentColor"
							d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
						></path>
					</svg>
				{:else}
					<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 19l9 2-9-18-9 18 9-2zm0 0v-8"
						/>
					</svg>
				{/if}
				Send
			</button>
		</form>
	</div>
</div>
