<script lang="ts">
import { goto } from '$app/navigation';
import { m } from '$lib/paraglide/messages.js';
import { formatDate } from '$lib/utils/date';
import { groupDocuments } from '$lib/utils/groupDocuments';
import GroupDivider from '$lib/components/GroupDivider.svelte';

let {
	documents,
	canWrite,
	error,
	total = 0,
	q = '',
	sort
}: {
	documents: {
		id: string;
		title?: string | null;
		originalFilename: string;
		documentDate?: string | null;
		location?: string | null;
		sender?: { firstName?: string | null; lastName: string; displayName: string } | null;
		receivers?: { firstName?: string | null; lastName: string; displayName: string }[];
		tags?: { id: string; name: string }[];
	}[];
	canWrite: boolean;
	error?: string | null;
	total?: number;
	q?: string;
	sort?: string;
} = $props();

const fallbackLabel = $derived(
	(sort ?? 'DATE') === 'DATE' ? m.docs_group_undated() : m.docs_group_unknown()
);
const groupedDocuments = $derived.by(() =>
	groupDocuments(documents, sort ?? 'DATE', fallbackLabel)
);
const showDividers = $derived(groupedDocuments.length >= 2);
</script>

<!-- DOCUMENT LIST HEADER -->
<div class="mb-2 flex justify-end">
	{#if canWrite}
		<a
			href="/documents/new"
			class="inline-flex items-center gap-1 text-sm font-medium text-ink-2 transition-colors hover:text-ink"
		>
			<img
				src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Add/Add-General-MD.svg"
				alt=""
				aria-hidden="true"
				class="h-4 w-4"
			/>
			{m.docs_btn_new()}
		</a>
	{/if}
</div>

<!-- RESULT COUNT -->
{#if total > 0}
	<p class="mb-3 font-sans text-base text-ink-2">{m.docs_result_count({ count: total })}</p>
{/if}

<!-- DOCUMENT LIST -->
<div class="border border-line bg-surface shadow-sm">
	{#if error}
		<div class="bg-red-50 p-8 text-center text-red-600">
			{error}
		</div>
	{:else if documents.length > 0}
		{#each groupedDocuments as group (group.label)}
			{#if showDividers}
				<GroupDivider label={group.label} />
			{/if}
			<ul class="divide-y divide-line-2">
				{#each group.documents as doc (doc.id)}
					<li class="group transition-colors duration-200 hover:bg-muted/50">
						<a href="/documents/{doc.id}" class="block p-6">
							<div class="flex flex-col gap-6 sm:flex-row">
								<!-- Main Info -->
								<div class="flex-1">
									<div class="mb-2 flex items-baseline justify-between">
										<h3 class="font-serif text-xl font-medium text-ink group-hover:underline">
											{doc.title || doc.originalFilename}
										</h3>
									</div>

									<!-- Metadata Row -->
									<div class="mb-4 flex flex-wrap gap-6 font-sans text-sm text-ink-2">
										<div class="flex items-center">
											<img
												src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Calendar/Calendar-Add-MD.svg"
												alt=""
												aria-hidden="true"
												class="mr-1.5 h-4 w-4"
											/>
											{doc.documentDate ? formatDate(doc.documentDate) : '—'}
										</div>
										{#if doc.location}
											<div class="flex items-center">
												<img
													src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Location-MD.svg"
													alt=""
													aria-hidden="true"
													class="mr-1.5 h-4 w-4"
												/>
												{doc.location}
											</div>
										{/if}
									</div>

									<!-- Sender/Receiver Info -->
									<div class="grid grid-cols-1 gap-4 font-serif text-sm sm:grid-cols-2">
										<div class="flex items-baseline">
											<span
												class="w-10 font-sans text-xs font-bold tracking-wide text-ink-3 uppercase"
												>{m.docs_list_from()}</span
											>
											{#if doc.sender}
												<span class="text-ink">{doc.sender.displayName}</span>
											{:else}
												<span class="text-ink-3 italic">{m.docs_list_unknown()}</span>
											{/if}
										</div>
										<div class="flex items-baseline">
											<span
												class="w-10 font-sans text-xs font-bold tracking-wide text-ink-3 uppercase"
												>{m.docs_list_to()}</span
											>
											{#if doc.receivers && doc.receivers.length > 0}
												<span class="text-ink">
													{doc.receivers.map((p) => p.displayName).join(', ')}
												</span>
											{:else}
												<span class="text-ink-3 italic">{m.docs_list_unknown()}</span>
											{/if}
										</div>
									</div>

									<!-- Tags Display -->
									{#if doc.tags && doc.tags.length > 0}
										<div class="mt-4 flex flex-wrap gap-2 pt-3">
											{#each doc.tags as tag (tag.id)}
												<button
													type="button"
													class="relative z-10 inline-flex cursor-pointer items-center rounded bg-muted px-2 py-1 text-[10px] font-bold tracking-widest text-ink uppercase transition-colors hover:bg-primary hover:text-primary-fg"
													onclick={(e) => {
														e.preventDefault();
														e.stopPropagation();
														goto(`/?tag=${encodeURIComponent(tag.name)}`);
													}}
												>
													{tag.name}
												</button>
											{/each}
										</div>
									{/if}
								</div>

								<!-- Arrow Icon -->
								<div
									class="hidden items-center text-ink-3 transition-colors group-hover:text-accent sm:flex"
								>
									<img
										src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Arrow/Arrow-Right-MD.svg"
										alt=""
										aria-hidden="true"
										class="h-6 w-6"
									/>
								</div>
							</div>
						</a>
					</li>
				{/each}
			</ul>
		{/each}
	{:else}
		<!-- Empty State -->
		<div class="p-16 text-center">
			<div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
				<img
					src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Mag-Glass-MD.svg"
					alt=""
					aria-hidden="true"
					class="h-6 w-6"
				/>
			</div>
			<h3 class="font-serif text-lg font-medium text-ink">{m.docs_empty_heading()}</h3>
			<p class="mt-1 font-sans text-sm text-ink-2">
				{q ? m.docs_empty_for_term({ term: q }) : m.docs_empty_text()}
			</p>
			<button
				onclick={() => goto('/')}
				class="mt-6 text-sm font-bold tracking-wide text-primary uppercase transition hover:text-ink-2"
			>
				{m.docs_empty_btn_clear()}
			</button>
		</div>
	{/if}
</div>
