<script lang="ts">
import { onMount, untrack } from 'svelte';
import PersonTypeahead from '$lib/person/PersonTypeahead.svelte';
import PersonMultiSelect from '$lib/person/PersonMultiSelect.svelte';
import FieldLabelBadge from '$lib/shared/primitives/FieldLabelBadge.svelte';
import { isoToGerman, handleGermanDateInput } from '$lib/shared/utils/date';
import { m } from '$lib/paraglide/messages.js';
import type { components } from '$lib/generated/api';
import type { DatePrecision } from '$lib/shared/utils/documentDate';

type Person = components['schemas']['Person'];

let {
	senderId = $bindable(''),
	selectedReceivers = $bindable<Person[]>([]),
	dateIso = $bindable(''),
	precision = $bindable<DatePrecision>('DAY'),
	endDateIso = $bindable(''),
	rawDate = '',
	initialDateIso = '',
	initialLocation = '',
	initialSenderName = '',
	suggestedDateIso = '',
	suggestedSenderName = '',
	hideDate = false,
	editMode = false
}: {
	senderId?: string;
	selectedReceivers?: Person[];
	dateIso?: string;
	precision?: DatePrecision;
	endDateIso?: string;
	rawDate?: string;
	initialDateIso?: string;
	initialLocation?: string;
	initialSenderName?: string;
	suggestedDateIso?: string;
	suggestedSenderName?: string;
	hideDate?: boolean;
	editMode?: boolean;
} = $props();

const PRECISIONS: { value: DatePrecision; label: () => string }[] = [
	{ value: 'DAY', label: m.date_precision_option_day },
	{ value: 'MONTH', label: m.date_precision_option_month },
	{ value: 'SEASON', label: m.date_precision_option_season },
	{ value: 'YEAR', label: m.date_precision_option_year },
	{ value: 'RANGE', label: m.date_precision_option_range },
	{ value: 'APPROX', label: m.date_precision_option_approx },
	{ value: 'UNKNOWN', label: m.date_precision_option_unknown }
];

const showEndDate = $derived(precision === 'RANGE');

// dateDisplay seeds from the bindable's value or initialDateIso once at mount
// and is then user-driven. onMount runs exactly once, so this never stomps
// the parent's dateIso on a later prop change.
let dateDisplay = $state('');
let dateDirty = $state(false);
let endDisplay = $state('');

onMount(() => {
	const seed = dateIso || initialDateIso;
	if (seed) {
		dateDisplay = isoToGerman(seed);
		if (!dateIso) dateIso = seed;
	}
	if (endDateIso) endDisplay = isoToGerman(endDateIso);
});

const dateInvalid = $derived(dateDirty && dateDisplay.length > 0 && dateIso === '');

function handleDateInput(e: Event) {
	const result = handleGermanDateInput(e);
	dateDisplay = result.display;
	dateIso = result.iso;
	dateDirty = true;
}

function handleEndDateInput(e: Event) {
	const result = handleGermanDateInput(e);
	endDisplay = result.display;
	endDateIso = result.iso;
}

$effect(() => {
	const suggested = suggestedDateIso;
	if (suggested && !untrack(() => dateDirty)) {
		dateDisplay = isoToGerman(suggested);
		dateIso = suggested;
	}
});
</script>

<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
	<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
		{m.doc_section_who_when()}
	</h2>

	<div class="grid grid-cols-1 gap-5 md:grid-cols-2">
		{#if !hideDate}
			<!-- Datum (required — row 1, col 1) -->
			<div data-testid="who-when-date">
				<label for="documentDate" class="mb-1 block text-sm font-medium text-ink-2"
					>{m.form_label_date()}*</label
				>
				<input
					id="documentDate"
					type="text"
					inputmode="numeric"
					value={dateDisplay}
					oninput={handleDateInput}
					placeholder={m.form_placeholder_date()}
					maxlength="10"
					class="block w-full rounded border border-line px-2 py-3 text-sm shadow-sm
                       {dateInvalid
						? 'border-red-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500'
						: 'focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring'}"
					aria-describedby={dateInvalid ? 'date-error' : undefined}
				/>
				<input type="hidden" name="documentDate" value={dateIso} />
				{#if dateInvalid}
					<p id="date-error" class="mt-1 text-xs text-red-600">{m.form_date_error()}</p>
				{/if}
			</div>
			<!-- Datumsgenauigkeit (precision) -->
			<div data-testid="who-when-precision">
				<label for="metaDatePrecision" class="mb-1 block text-sm font-medium text-ink-2">
					{m.form_label_date_precision()}
				</label>
				<select
					id="metaDatePrecision"
					name="metaDatePrecision"
					bind:value={precision}
					class="block min-h-[48px] w-full rounded border border-line px-2 py-3 text-sm shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
				>
					{#each PRECISIONS as p (p.value)}
						<option value={p.value}>{p.label()}</option>
					{/each}
				</select>
			</div>

			<!-- Enddatum: progressive disclosure, revealed only for RANGE, announced politely. -->
			<div aria-live="polite">
				{#if showEndDate}
					<div data-testid="who-when-end-date">
						<label for="metaDateEnd" class="mb-1 block text-sm font-medium text-ink-2">
							{m.form_label_date_end()}
						</label>
						<input
							id="metaDateEnd"
							type="text"
							inputmode="numeric"
							value={endDisplay}
							oninput={handleEndDateInput}
							placeholder={m.form_placeholder_date()}
							maxlength="10"
							class="block min-h-[48px] w-full rounded border border-line px-2 py-3 text-sm shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
						/>
					</div>
				{/if}
			</div>
			<input type="hidden" name="metaDateEnd" value={showEndDate ? endDateIso : ''} />

			<!-- Originaltext (read-only raw cell): labelled static text, not a disabled input. -->
			{#if rawDate && rawDate.trim().length > 0}
				<div data-testid="who-when-raw">
					<p class="mb-1 block text-sm font-medium text-ink-2">{m.date_original_label()}</p>
					<p class="font-sans text-sm text-ink">{rawDate}</p>
					<input type="hidden" name="metaDateRaw" value={rawDate} />
				</div>
			{/if}
		{/if}

		<!-- Absender (required in upload mode — row 1, col 2) -->
		<div>
			<PersonTypeahead
				name="senderId"
				label={m.form_label_sender()}
				required={!editMode}
				bind:value={senderId}
				initialName={initialSenderName}
				suggestedName={suggestedSenderName}
				badge={editMode ? 'replace' : undefined}
			/>
		</div>

		<!-- Empfänger (optional — row 2, col 1) -->
		<div>
			<p class="mb-1 block text-sm font-medium text-ink-2">
				{m.form_label_receivers()}
				{#if editMode}<FieldLabelBadge variant="additive" />{/if}
			</p>
			<PersonMultiSelect bind:selectedPersons={selectedReceivers} />
		</div>

		{#if !editMode}
			<!-- Ort (optional — row 2, col 2). Hidden in editMode: meta_location is
				 NOT bulk-editable per the issue spec; the three editable location
				 fields live in DescriptionSection. -->
			<div>
				<label for="location" class="mb-1 block text-sm font-medium text-ink-2"
					>{m.form_label_location()}</label
				>
				<input
					id="location"
					type="text"
					name="location"
					value={initialLocation}
					placeholder={m.form_placeholder_location()}
					class="block w-full rounded border border-line px-2 py-3 text-sm shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
				/>
			</div>
		{/if}
	</div>
</div>
