<script lang="ts">
import { onMount, untrack } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
import type { Comment, FlatMessage } from '$lib/types';
import MentionEditor from '$lib/components/MentionEditor.svelte';
import CommentMessage from '$lib/components/CommentMessage.svelte';
import { extractContent } from '$lib/utils/mention';
type Props = {
	documentId: string;
	annotationId?: string | null;
	blockId?: string | null;
	initialComments?: Comment[];
	loadOnMount?: boolean;
	canComment: boolean;
	currentUserId: string | null;
	quotedText?: string | null;
	showCompose?: boolean;
	onCountChange?: (count: number) => void;
};

let {
	documentId,
	annotationId = null,
	blockId = null,
	initialComments = [],
	loadOnMount = false,
	canComment,
	currentUserId = null,
	quotedText = null,
	showCompose = true,
	onCountChange
}: Props = $props();

let comments: Comment[] = $state(untrack(() => [...initialComments]));
let newText: string = $state('');
let posting: boolean = $state(false);
let newMentionCandidates: MentionDTO[] = $state([]);
let editingId: string | null = $state(null);
let editText: string = $state('');

const commentsBase = $derived(
	blockId
		? `/api/documents/${documentId}/transcription-blocks/${blockId}/comments`
		: annotationId
			? `/api/documents/${documentId}/annotations/${annotationId}/comments`
			: `/api/documents/${documentId}/comments`
);

const flatMessages = $derived(
	comments.flatMap((thread) => [thread as FlatMessage, ...(thread.replies as FlatMessage[])])
);

$effect(() => {
	if (quotedText && quotedText.trim()) {
		newText = `> "${quotedText}"\n\n`;
	}
});

function isOwn(c: { authorId: string | null }): boolean {
	return currentUserId !== null && c.authorId === currentUserId;
}

async function reload() {
	try {
		const res = await fetch(commentsBase);
		if (res.ok) {
			comments = await res.json();
			const total = comments.reduce((s, c) => s + 1 + c.replies.length, 0);
			onCountChange?.(total);
		}
	} catch {
		/* ignore */
	}
}

async function postComment() {
	const text = newText.trim();
	if (!text || posting) return;
	posting = true;
	try {
		const { content, mentionedUserIds } = extractContent(text, newMentionCandidates);
		const res = await fetch(commentsBase, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ content, mentionedUserIds })
		});
		if (res.ok) {
			newText = '';
			newMentionCandidates = [];
			await reload();
		}
	} finally {
		posting = false;
	}
}

function startEdit(msg: FlatMessage) {
	editingId = msg.id;
	editText = msg.content;
}

async function saveEdit(commentId: string) {
	const text = editText.trim();
	if (!text || posting) return;
	posting = true;
	try {
		const res = await fetch(`/api/documents/${documentId}/comments/${commentId}`, {
			method: 'PATCH',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ content: text })
		});
		if (res.ok) {
			editingId = null;
			editText = '';
			await reload();
		}
	} finally {
		posting = false;
	}
}

function cancelEdit() {
	editingId = null;
	editText = '';
}

function handleEditKeydown(e: KeyboardEvent, commentId: string) {
	if (e.key === 'Enter' && !e.shiftKey) {
		e.preventDefault();
		saveEdit(commentId);
	} else if (e.key === 'Escape') {
		e.stopPropagation();
		cancelEdit();
	}
}

async function deleteComment(commentId: string) {
	if (posting) return;
	posting = true;
	try {
		const res = await fetch(`/api/documents/${documentId}/comments/${commentId}`, {
			method: 'DELETE'
		});
		if (res.ok) {
			await reload();
		}
	} finally {
		posting = false;
	}
}

onMount(() => {
	if (loadOnMount) {
		reload();
	} else {
		const total = initialComments.reduce((s, c) => s + 1 + c.replies.length, 0);
		onCountChange?.(total);
	}
});
</script>

{#if flatMessages.length === 0}
	<p class="text-sm text-ink-3 italic">{m.comment_empty_hint()}</p>
{:else}
	<div class="rounded border-l-2 border-accent bg-muted p-2">
		<div class="mb-2 flex items-center gap-1.5 font-sans text-sm font-semibold text-ink-2">
			<svg
				class="h-3.5 w-3.5"
				viewBox="0 0 24 24"
				fill="none"
				stroke="currentColor"
				stroke-width="2"
			>
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					d="M2.25 12.76c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 011.037-.443 48.282 48.282 0 005.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"
				/>
			</svg>
			{flatMessages.length}
			{flatMessages.length === 1 ? 'Kommentar' : 'Kommentare'}
		</div>

		<div role="log" class="space-y-2">
			{#each flatMessages as msg (msg.id)}
				<CommentMessage
					message={msg}
					isOwn={isOwn(msg)}
					isEditing={editingId === msg.id}
					editText={editText}
					onEdit={() => startEdit(msg)}
					onDelete={() => deleteComment(msg.id)}
					onEditTextChange={(text) => { editText = text; }}
					onEditKeydown={(e) => handleEditKeydown(e, msg.id)}
				/>
			{/each}
		</div>
	</div>
{/if}

{#if canComment && (showCompose || flatMessages.length > 0)}
	<div class="mt-2">
		<MentionEditor
			bind:value={newText}
			bind:mentionCandidates={newMentionCandidates}
			rows={1}
			placeholder={m.comment_placeholder()}
			disabled={posting}
			onsubmit={postComment}
		/>
	</div>
{/if}
