<script lang="ts">
	import { liveQuery } from 'dexie';
	import { db } from '$lib/db/schema';
	import { updateTopic } from '$lib/db/repositories';
	import type { Topic, AgendaContext } from '@ka-note/shared';

	interface Props {
		contextId: string;
	}
	let { contextId }: Props = $props();

	const isDailyLog = $derived(contextId === 'daily-log');

	const snoozedTopics = liveQuery(() =>
		isDailyLog
			? db.topics.filter(t => !t.deletedAt && t.status === 'snoozed' && !!t.snoozeUntil).toArray()
			: db.topics.where('contextId').equals(contextId)
				.filter(t => !t.deletedAt && t.status === 'snoozed' && !!t.snoozeUntil)
				.toArray()
	);

	const contexts = liveQuery(() => db.contexts.filter(c => !c.deletedAt).toArray());

	const contextMap = $derived(
		new Map(($contexts ?? []).map((c: AgendaContext) => [c.id, c.name]))
	);

	const grouped = $derived(() => {
		const topics = $snoozedTopics ?? [];
		const groups = new Map<string, Topic[]>();
		for (const t of topics) {
			const date = t.snoozeUntil!;
			const list = groups.get(date) ?? [];
			list.push(t);
			groups.set(date, list);
		}
		return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b));
	});

	function reactivate(id: string) {
		updateTopic(id, { snoozeUntil: null, status: 'active', isNew: false });
	}
</script>

{#each grouped() as [date, topics]}
	<div class="mb-6">
		<div class="mb-2 text-sm font-bold text-accent">{date}</div>
		{#each topics as topic (topic.id)}
			<div class="mb-2 rounded-lg border-l-[5px] border-l-muted bg-card-bg opacity-60">
				<div class="flex items-center justify-between px-5 py-4">
					<div>
						<span class="text-lg font-bold">{topic.title}</span>
						{#if isDailyLog && topic.contextId !== 'daily-log'}
							<span class="ml-2 text-xs text-muted">{contextMap.get(topic.contextId) ?? topic.contextId}</span>
						{/if}
					</div>
					<button
						class="rounded bg-success px-4 py-2 font-bold text-white"
						onclick={() => reactivate(topic.id)}
					>
						Reaktivieren
					</button>
				</div>
			</div>
		{/each}
	</div>
{:else}
	<div class="text-center text-muted">Keine verschobenen Themen.</div>
{/each}
