<script lang="ts">
import { onMount } from 'svelte';
import { enhance } from '$app/forms';
import { m } from '$lib/paraglide/messages.js';
import PersonTypeahead from '$lib/person/PersonTypeahead.svelte';
import RelationshipDateField from '$lib/person/relationship/RelationshipDateField.svelte';
import type { components } from '$lib/generated/api';
import type { DatePrecision } from '$lib/shared/utils/documentDate';

type RelationshipDTO = components['schemas']['RelationshipDTO'];
type RelationType = NonNullable<RelationshipDTO['relationType']>;

export type RelFormData = {
	relatedPersonId: string;
	relationType: RelationType;
	fromDate?: string;
	fromDatePrecision?: DatePrecision;
	toDate?: string;
	toDatePrecision?: DatePrecision;
	notes?: string;
};

interface Props {
	personId: string;
	// When present the form is an EDIT: pre-filled and posting to ?/updateRelationship.
	relationship?: RelationshipDTO;
	onSubmit?: (data: RelFormData) => Promise<void>;
	onClose?: () => void;
}

let { personId, relationship, onSubmit, onClose }: Props = $props();

const isEdit = $derived(relationship != null);

let open = $state(false);
let addType = $state<RelationType>('PARENT_OF');
let addRelatedPersonId = $state('');
let addRelatedPersonName = $state('');
let notes = $state('');
let callbackError = $state<string | null>(null);
let submitting = $state(false);

// Seed once at mount (reading props in a closure avoids state_referenced_locally).
// The parent re-creates this form per edited row, so the relationship never
// changes under a live instance.
onMount(() => {
	if (!relationship) return;
	open = true;
	addType = relationship.relationType ?? 'PARENT_OF';
	const viewpointIsSubject = relationship.personId === personId;
	addRelatedPersonId =
		(viewpointIsSubject ? relationship.relatedPersonId : relationship.personId) ?? '';
	addRelatedPersonName =
		(viewpointIsSubject ? relationship.relatedPersonDisplayName : relationship.personDisplayName) ??
		'';
	notes = relationship.notes ?? '';
});

const selfError = $derived(
	addRelatedPersonId !== '' && addRelatedPersonId === personId ? m.relation_error_self() : null
);

const submitDisabled = $derived(selfError !== null || addRelatedPersonId === '');

function reset() {
	addType = 'PARENT_OF';
	addRelatedPersonId = '';
	addRelatedPersonName = '';
	notes = '';
	callbackError = null;
}

function cancel() {
	if (isEdit) {
		onClose?.();
		return;
	}
	open = false;
	reset();
}

async function handleCallbackSubmit(event: SubmitEvent) {
	event.preventDefault();
	if (submitDisabled || !onSubmit) return;
	const fd = new FormData(event.currentTarget as HTMLFormElement);
	const fromDate = (fd.get('fromDate') as string) || undefined;
	const toDate = (fd.get('toDate') as string) || undefined;
	const data: RelFormData = {
		relatedPersonId: addRelatedPersonId,
		relationType: addType,
		fromDate,
		fromDatePrecision: fromDate ? (fd.get('fromDatePrecision') as DatePrecision) : undefined,
		toDate,
		toDatePrecision: toDate ? (fd.get('toDatePrecision') as DatePrecision) : undefined,
		notes: (fd.get('notes') as string)?.trim() || undefined
	};
	submitting = true;
	try {
		await onSubmit(data);
		open = false;
		reset();
	} catch {
		callbackError = m.error_internal_error();
	} finally {
		submitting = false;
	}
}
</script>

{#snippet formFields()}
	<div class="grid gap-3 md:grid-cols-2">
		<label class="block">
			<span class="font-sans text-xs font-medium text-ink-2">{m.relation_form_field_type()}</span>
			<select
				name="relationType"
				bind:value={addType}
				class="mt-1 block w-full rounded-sm border border-line bg-surface px-2 py-1.5 text-sm text-ink focus:border-primary focus:outline-none"
			>
				<optgroup label={m.relation_form_group_family()}>
					<option value="PARENT_OF">{m.relation_parent_of()}</option>
					<option value="SPOUSE_OF">{m.relation_spouse_of()}</option>
					<option value="SIBLING_OF">{m.relation_sibling_of()}</option>
				</optgroup>
				<optgroup label={m.relation_form_group_social()}>
					<option value="FRIEND">{m.relation_friend()}</option>
					<option value="COLLEAGUE">{m.relation_colleague()}</option>
					<option value="EMPLOYER">{m.relation_employer()}</option>
					<option value="DOCTOR">{m.relation_doctor()}</option>
					<option value="NEIGHBOR">{m.relation_neighbor()}</option>
					<option value="OTHER">{m.relation_other()}</option>
				</optgroup>
			</select>
		</label>
		<div>
			<PersonTypeahead
				name="relatedPersonId"
				label="Person"
				bind:value={addRelatedPersonId}
				initialName={addRelatedPersonName}
				excludePersonId={personId}
				compact
			/>
		</div>
	</div>
	<div class="mt-3 grid gap-3 md:grid-cols-2">
		<RelationshipDateField
			name="fromDate"
			legend={m.relation_label_from_date()}
			initialIso={relationship?.fromDate ?? ''}
			initialPrecision={relationship?.fromDatePrecision ?? null}
		/>
		<RelationshipDateField
			name="toDate"
			legend={m.relation_label_to_date()}
			initialIso={relationship?.toDate ?? ''}
			initialPrecision={relationship?.toDatePrecision ?? null}
		/>
	</div>
	<label class="mt-3 block">
		<span class="font-sans text-xs font-medium text-ink-2">{m.relation_label_notes()}</span>
		<textarea
			name="notes"
			maxlength="2000"
			rows="2"
			bind:value={notes}
			placeholder={m.relation_notes_placeholder()}
			class="mt-1 block w-full rounded-sm border border-line bg-surface px-2 py-1.5 font-serif text-sm text-ink-3 focus:border-primary focus:outline-none"
		></textarea>
	</label>
	{#if selfError}
		<p class="mt-2 text-xs text-red-700" role="alert">{selfError}</p>
	{/if}
	{#if callbackError}
		<p class="mt-2 text-xs text-red-700" role="alert">{callbackError}</p>
	{/if}
	<div class="mt-3 flex items-center justify-end gap-2">
		<button
			type="button"
			onclick={cancel}
			class="rounded-sm border border-line bg-surface px-3 py-1.5 font-sans text-xs font-medium text-ink-2 transition hover:bg-muted"
		>
			{m.relation_btn_cancel()}
		</button>
		<button
			type="submit"
			disabled={submitDisabled || submitting}
			aria-busy={submitting}
			class="inline-flex items-center gap-1.5 rounded-sm bg-primary px-3 py-1.5 font-sans text-xs font-medium text-primary-fg transition hover:bg-primary/80 disabled:opacity-40"
		>
			{#if submitting}
				<span
					class="h-3 w-3 animate-spin rounded-full border-2 border-primary-fg/40 border-t-primary-fg"
					data-testid="submit-spinner"
					aria-hidden="true"
				></span>
			{/if}
			{isEdit ? m.relation_btn_save() : m.relation_btn_add()}
		</button>
	</div>
{/snippet}

{#if !open}
	<button
		type="button"
		onclick={() => (open = true)}
		class="mt-2 inline-flex items-center gap-1 font-sans text-xs font-medium text-ink-2 hover:text-ink"
	>
		{m.stammbaum_panel_add_rel()}
	</button>
{:else if onSubmit}
	<form onsubmit={handleCallbackSubmit} class="mt-3 rounded-sm border border-line bg-muted/40 p-3">
		{@render formFields()}
	</form>
{:else}
	<form
		method="POST"
		action={isEdit ? '?/updateRelationship' : '?/addRelationship'}
		use:enhance={() => {
			submitting = true;
			return async ({ result, update }) => {
				await update();
				submitting = false;
				if (result.type === 'success') {
					if (isEdit) {
						onClose?.();
					} else {
						open = false;
						reset();
					}
				}
			};
		}}
		class="mt-3 rounded-sm border border-line bg-muted/40 p-3"
	>
		{#if relationship}
			<input type="hidden" name="relId" value={relationship.id} />
		{/if}
		{@render formFields()}
	</form>
{/if}
