<script lang="ts">
import { enhance } from '$app/forms';
import { replaceState } from '$app/navigation';
import { page } from '$app/state';
import { m } from '$lib/paraglide/messages.js';
import { createUnsavedWarning } from '$lib/shared/hooks/useUnsavedWarning.svelte';
import UnsavedWarningBanner from '$lib/shared/primitives/UnsavedWarningBanner.svelte';
import TagParentPicker from '$lib/tag/TagParentPicker.svelte';
import TagAncestry from './TagAncestry.svelte';
import TagChildrenPreview from './TagChildrenPreview.svelte';
import TagMergeZone from './TagMergeZone.svelte';
import TagDeleteGuard from './TagDeleteGuard.svelte';

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

const unsaved = createUnsavedWarning();

function getInitialParentId() {
	return data.tag.parentId ?? '';
}
function getInitialColor() {
	return data.tag.color ?? '';
}
function getInitialParentName() {
	if (!data.tag.parentId) return '';
	return data.tags.find((t: { id: string }) => t.id === data.tag.parentId)?.name ?? '';
}

let parentId = $state(getInitialParentId());
let selectedColor = $state(getInitialColor());
let parentName = $state(getInitialParentName());

// Reset state when navigating between tags client-side
$effect(() => {
	void data.tag.id;
	parentId = data.tag.parentId ?? '';
	selectedColor = data.tag.color ?? '';
	parentName = getInitialParentName();
});

$effect(() => {
	if (form?.success) unsaved.clearOnSuccess();
});

$effect(() => {
	if (data.mergeSuccess) {
		replaceState(page.url.pathname, {});
	}
});

const colors = [
	'sage',
	'sienna',
	'amber',
	'slate',
	'violet',
	'rose',
	'cobalt',
	'moss',
	'sand',
	'coral'
];
</script>

<div class="flex flex-1 flex-col overflow-hidden">
	<!-- Header -->
	<div class="flex items-center border-b border-line px-5 py-3">
		<a
			href="/admin/tags"
			aria-label="Zurück zur Tag-Übersicht"
			class="mr-3 inline-flex items-center gap-1 text-xs text-ink-3 hover:text-ink md:hidden"
		>
			<svg
				class="h-4 w-4"
				fill="none"
				viewBox="0 0 24 24"
				stroke="currentColor"
				stroke-width="2"
				aria-hidden="true"
			>
				<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
			</svg>
		</a>
		<h2 class="flex-1 font-sans text-sm font-bold text-ink">
			{m.admin_tag_edit_heading({ name: data.tag.name })}
		</h2>
	</div>

	<!-- Scrollable body -->
	<div class="flex-1 overflow-y-auto px-5 py-5">
		<!-- TagAncestry breadcrumb -->
		<TagAncestry tag={data.tag} allTags={data.tags} />

		{#if unsaved.showUnsavedWarning}
			<UnsavedWarningBanner onDiscard={unsaved.discard} />
		{/if}
		{#if data.mergeSuccess}
			<div
				class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700"
				role="status"
				aria-live="polite"
			>
				{m.admin_tag_merge_success()}
			</div>
		{/if}
		{#if form?.success}
			<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
				{m.admin_tag_updated()}
			</div>
		{/if}
		{#if form?.error}
			<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
				{form.error}
			</div>
		{/if}

		<!-- Rename form -->
		<form
			id="edit-tag-form"
			method="POST"
			action="?/update"
			use:enhance={() => async ({ update }) => { await update({ reset: false }); }}
			oninput={unsaved.markDirty}
			class="mb-5"
		>
			<!-- Name card -->
			<div class="mb-5 rounded-sm border border-line bg-surface p-5 shadow-sm">
				<h3 class="mb-3 text-xs font-bold tracking-widest text-ink-3 uppercase">
					{m.admin_col_name()}
				</h3>
				<p class="mb-3 text-xs text-amber-700">{m.admin_tags_warning()}</p>
				<input
					type="text"
					name="name"
					value={data.tag.name}
					required
					class="w-full rounded-sm border border-line bg-surface px-3 py-2 text-sm text-ink focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
				/>
			</div>

			<!-- Parent selector (TagParentPicker) -->
			<div class="mb-5 rounded-sm border border-line bg-surface p-5 shadow-sm">
				<h3 class="mb-3 text-xs font-bold tracking-widest text-ink-3 uppercase">
					Übergeordnetes Schlagwort
				</h3>
				<TagParentPicker
					name="parentId"
					bind:value={parentId}
					excludeIds={[data.tag.id]}
					initialName={parentName}
					allTags={data.tags}
				/>
			</div>

			<!-- Color picker (only when no parent) -->
			{#if parentId === ''}
				<div
					data-testid="color-picker"
					class="mb-5 rounded-sm border border-line bg-surface p-5 shadow-sm"
				>
					<h3 class="mb-3 text-xs font-bold tracking-widest text-ink-3 uppercase">Farbe</h3>
					<div class="mb-3 flex flex-wrap gap-2" role="group" aria-label="Farbe auswählen">
						{#each colors as colorName (colorName)}
							<button
								type="button"
								data-testid="color-swatch-{colorName}"
								aria-pressed={selectedColor === colorName ? 'true' : 'false'}
								aria-label={colorName}
								style="background-color: var(--c-tag-{colorName})"
								class="h-8 w-8 rounded-full {selectedColor === colorName ? 'ring-2 ring-current ring-offset-2' : ''}"
								onclick={() => { selectedColor = selectedColor === colorName ? '' : colorName; }}
							></button>
						{/each}
						<button
							type="button"
							class="flex h-8 w-8 items-center justify-center rounded-full border border-line bg-surface text-sm text-ink-3 hover:text-ink"
							onclick={() => { selectedColor = ''; }}
							aria-label="Farbe zurücksetzen">×</button
						>
					</div>
					<input type="hidden" name="color" value={selectedColor} />
				</div>
			{:else}
				<input type="hidden" name="color" value="" />
			{/if}
		</form>

		<!-- Children preview -->
		<TagChildrenPreview tag={data.tag} allTags={data.tags} />

		<!-- Merge zone -->
		<TagMergeZone tag={data.tag} allTags={data.tags} form={form} />

		<!-- Delete guard -->
		<TagDeleteGuard tag={data.tag} allTags={data.tags} />
	</div>

	<!-- Footer -->
	<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
		<a
			href="/admin/tags"
			class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
		>
			{m.btn_cancel()}
		</a>
		<button
			type="submit"
			form="edit-tag-form"
			class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
		>
			{m.btn_save()}
		</button>
	</div>
</div>
