<script lang="ts">
import { enhance } from '$app/forms';
import { m } from '$lib/paraglide/messages.js';
import { getConfirmService } from '$lib/shared/services/confirm.svelte';

interface Props {
	aliases: Array<{
		id: string;
		lastName: string;
		firstName?: string | null;
		type: string;
		sortOrder: number;
	}>;
	canWrite: boolean;
	aliasError?: string | null;
}

let { aliases, canWrite, aliasError = null }: Props = $props();

const { confirm } = getConfirmService();

let sorted = $derived([...aliases].sort((a, b) => a.sortOrder - b.sortOrder));

let removeFormEl = $state<HTMLFormElement | null>(null);
let aliasIdInputEl = $state<HTMLInputElement | null>(null);

function typeLabel(type: string): string {
	switch (type) {
		case 'BIRTH':
			return m.person_alias_type_BIRTH();
		case 'WIDOWED':
			return m.person_alias_type_WIDOWED();
		case 'DIVORCED':
			return m.person_alias_type_DIVORCED();
		default:
			return m.person_alias_type_OTHER();
	}
}

async function handleDelete(id: string) {
	const confirmed = await confirm({
		title: m.person_alias_delete_title(),
		body: m.person_alias_delete_body(),
		destructive: true
	});
	if (confirmed && removeFormEl) {
		if (aliasIdInputEl) aliasIdInputEl.value = id;
		removeFormEl.requestSubmit();
	}
}
</script>

<div class="mt-6 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.person_alias_heading()}
	</h2>

	{#if aliasError}
		<p class="mb-3 text-sm text-red-600">{aliasError}</p>
	{/if}

	{#if sorted.length === 0}
		<p class="text-sm text-ink-2 italic">{m.person_alias_empty()}</p>
	{:else}
		<ul class="space-y-2">
			{#each sorted as alias (alias.id)}
				<li class="flex items-center justify-between">
					<span>
						<span class="text-ink-2 italic">{typeLabel(alias.type)}</span>
						<span class="font-serif text-ink">
							{#if alias.firstName}{alias.firstName}{/if}
							{alias.lastName}
						</span>
					</span>
					{#if canWrite}
						<button
							type="button"
							onclick={() => handleDelete(alias.id)}
							aria-label="{m.person_alias_btn_delete()} {alias.lastName}"
							class="ml-4 inline-flex min-h-[44px] min-w-[44px] items-center justify-center text-red-400 transition-colors hover:text-red-600"
						>
							<svg
								class="h-4 w-4"
								fill="none"
								stroke="currentColor"
								viewBox="0 0 24 24"
								aria-hidden="true"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M6 18L18 6M6 6l12 12"
								/>
							</svg>
						</button>
					{/if}
				</li>
			{/each}
		</ul>
	{/if}

	{#if canWrite}
		<!-- Hidden form for alias removal — submitted programmatically after ConfirmService dialog -->
		<form bind:this={removeFormEl} method="POST" action="?/removeAlias" use:enhance class="hidden">
			<input bind:this={aliasIdInputEl} type="hidden" name="aliasId" value="" />
		</form>

		<div class="mt-4 border-t border-line pt-4">
			<h3 class="mb-3 text-xs font-bold tracking-widest text-ink-3 uppercase">
				{m.person_alias_add_heading()}
			</h3>

			<form method="POST" action="?/addAlias" use:enhance>
				<div class="grid gap-3 md:grid-cols-2">
					<label class="block">
						<span class="text-xs font-medium text-ink-2">{m.person_alias_label_type()}</span>
						<select
							name="type"
							class="mt-1 block w-full rounded-sm border border-line bg-surface px-3 py-2 text-sm text-ink focus:border-primary focus:outline-none"
						>
							<option value="BIRTH">{m.person_alias_type_BIRTH()}</option>
							<option value="WIDOWED">{m.person_alias_type_WIDOWED()}</option>
							<option value="DIVORCED">{m.person_alias_type_DIVORCED()}</option>
							<option value="OTHER">{m.person_alias_type_OTHER()}</option>
						</select>
					</label>

					<label class="block">
						<span class="text-xs font-medium text-ink-2">{m.person_alias_label_last_name()}</span>
						<input
							type="text"
							name="lastName"
							required
							class="mt-1 block w-full rounded-sm border border-line bg-surface px-3 py-2 text-sm text-ink focus:border-primary focus:outline-none"
						/>
					</label>

					<label class="block">
						<span class="text-xs font-medium text-ink-2">{m.person_alias_label_first_name()}</span>
						<input
							type="text"
							name="firstName"
							class="mt-1 block w-full rounded-sm border border-line bg-surface px-3 py-2 text-sm text-ink focus:border-primary focus:outline-none"
						/>
					</label>

					<div class="flex items-end">
						<button
							type="submit"
							class="w-full rounded-sm bg-primary px-4 py-2 text-sm font-medium text-primary-fg transition-colors hover:bg-primary/80"
						>
							{m.person_alias_btn_add()}
						</button>
					</div>
				</div>
			</form>
		</div>
	{/if}
</div>
