<script lang="ts">
import { enhance } from '$app/forms';
import { onMount, untrack } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
import DocumentViewer from '$lib/components/DocumentViewer.svelte';
import WhoWhenSection from '$lib/components/document/WhoWhenSection.svelte';
import DescriptionSection from '$lib/components/document/DescriptionSection.svelte';

let { data, form } = $props();

const doc = $derived(data.document);

// File preview state
let fileUrl = $state('');
let fileError = $state('');
let isLoading = $state(false);

let navHeight = $state(0);
onMount(() => {
	navHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 0;
});

// Dummy bindable state required by DocumentViewer
let annotateMode = $state(false);
let activeAnnotationId = $state<string | null>(null);
let activeAnnotationPage = $state<number | null>(null);

$effect(() => {
	if (doc?.id && doc?.filePath) {
		loadFile(doc.id);
	}
});

async function loadFile(id: string) {
	isLoading = true;
	fileError = '';
	fileUrl = '';
	try {
		const response = await fetch(`/api/documents/${id}/file`);
		if (!response.ok) throw new Error('Fehler');
		const blob = await response.blob();
		fileUrl = URL.createObjectURL(blob);
	} catch {
		fileError = m.doc_file_error_preview();
	} finally {
		isLoading = false;
	}
}

// Form state
let tags = $state(untrack(() => doc.tags?.map((t: { name: string }) => t.name) ?? []));
let senderId = $state(untrack(() => doc.sender?.id ?? ''));
let selectedReceivers = $state(untrack(() => doc.receivers ?? []));
</script>

<svelte:head>
	<title>{doc.title || doc.originalFilename || 'Dokument'} — Anreicherung</title>
</svelte:head>

<div class="fixed inset-x-0 bottom-0 flex flex-col" style="top: {navHeight}px">
	<!-- Top bar -->
	<div class="flex items-center justify-between border-b border-line bg-surface px-6 py-3">
		<a
			href="/enrich"
			class="group inline-flex items-center font-sans text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
		>
			<img
				src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Arrow/Arrow-Left-MD.svg"
				alt=""
				aria-hidden="true"
				class="mr-2 h-4 w-4 transform transition-transform group-hover:-translate-x-1"
			/>
			{m.enrich_back_to_list()}
		</a>

		<p class="max-w-sm truncate text-center font-serif text-sm font-medium text-ink">
			{doc.title || doc.originalFilename}
		</p>

		<p class="font-sans text-xs text-ink-3">
			{m.enrich_progress({ count: data.incompleteCount })}
		</p>
	</div>

	<!-- Main content -->
	<div class="flex flex-1 overflow-hidden">
		<!-- Left: PDF preview (60%) -->
		<div class="relative flex-[6] overflow-hidden border-r border-line">
			<DocumentViewer
				doc={doc}
				fileUrl={fileUrl}
				isLoading={isLoading}
				error={fileError}
				bind:annotateMode={annotateMode}
				bind:activeAnnotationId={activeAnnotationId}
				bind:activeAnnotationPage={activeAnnotationPage}
				onAnnotationClick={() => {}}
			/>
		</div>

		<!-- Right: form (40%) -->
		<div class="flex flex-[4] flex-col overflow-hidden">
			{#if form?.error}
				<div class="border-b border-red-200 bg-red-50 px-6 py-3 text-sm text-red-700">
					{form.error}
				</div>
			{/if}

			<form
				id="save-form"
				method="POST"
				action="?/save"
				enctype="multipart/form-data"
				use:enhance
				class="flex-1 space-y-5 overflow-y-auto p-6"
			>
				<WhoWhenSection
					bind:senderId={senderId}
					bind:selectedReceivers={selectedReceivers}
					initialDateIso={doc.documentDate ?? ''}
					initialLocation={doc.location ?? ''}
					initialSenderName={doc.sender
						? `${doc.sender.firstName} ${doc.sender.lastName}`
						: ''}
				/>
				<DescriptionSection bind:tags={tags} initialTitle={doc.title ?? ''} titleRequired={true} />
			</form>

			<!-- Skip form (outside main form to avoid nesting) -->
			<form id="skip-form" method="POST" action="?/skip" use:enhance></form>

			<!-- Action bar -->
			<div class="flex items-center justify-between gap-3 border-t border-line bg-surface p-4">
				<!-- Skip button linked to skip-form -->
				<button
					type="submit"
					form="skip-form"
					class="font-sans text-sm font-medium text-brand-navy/60 transition-colors hover:text-brand-navy"
				>
					{m.enrich_skip()}
				</button>

				<div class="flex items-center gap-3">
					<!-- Save -->
					<button
						type="submit"
						form="save-form"
						formaction="?/save"
						class="rounded-sm border border-gray-300 px-5 py-2 font-sans text-xs font-bold tracking-widest text-gray-600 uppercase transition-colors hover:bg-gray-50"
					>
						{m.btn_save()}
					</button>

					<!-- Save & mark as reviewed -->
					<button
						type="submit"
						form="save-form"
						formaction="?/saveAndReview"
						class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-colors hover:bg-primary/90"
					>
						{m.btn_save_and_mark_reviewed()}
					</button>
				</div>
			</div>
		</div>
	</div>
</div>
