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

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

function isoToGerman(iso: string | undefined): string {
	if (!iso) return '';
	const match = iso.match(/^(\d{4})-(\d{2})-(\d{2})$/);
	if (!match) return '';
	return `${match[3]}.${match[2]}.${match[1]}`;
}

function germanToIso(german: string): string {
	const match = german.match(/^(\d{2})\.(\d{2})\.(\d{4})$/);
	if (!match) return '';
	return `${match[3]}-${match[2]}-${match[1]}`;
}

let birthDateDisplay = $state(untrack(() => isoToGerman(data.editUser?.birthDate)));
let birthDateIso = $state(untrack(() => data.editUser?.birthDate ?? ''));

function handleBirthDateInput(e: Event) {
	const input = e.target as HTMLInputElement;
	const digits = input.value.replace(/\D/g, '').slice(0, 8);
	let formatted: string;
	if (digits.length <= 2) {
		formatted = digits;
	} else if (digits.length <= 4) {
		formatted = `${digits.slice(0, 2)}.${digits.slice(2)}`;
	} else {
		formatted = `${digits.slice(0, 2)}.${digits.slice(2, 4)}.${digits.slice(4)}`;
	}
	input.value = formatted;
	birthDateDisplay = formatted;
	birthDateIso = germanToIso(formatted);
}
</script>

<div class="mx-auto max-w-3xl px-4 py-8 sm:px-6 lg:px-8">
	<a
		href="/admin"
		class="group mb-4 inline-flex items-center text-xs font-bold tracking-widest text-gray-500 uppercase transition-colors hover:text-brand-navy"
	>
		<svg
			class="mr-2 h-4 w-4 transform transition-transform group-hover:-translate-x-1"
			fill="none"
			viewBox="0 0 24 24"
			stroke="currentColor"
			stroke-width="2"
		>
			<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
		</svg>
		{m.btn_back_to_overview()}
	</a>

	<h1 class="mb-6 font-serif text-3xl font-bold text-brand-navy">
		{m.admin_user_edit_heading({ username: data.editUser.username })}
	</h1>

	{#if form?.success}
		<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
			{m.admin_user_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}

	<form method="POST" use:enhance class="space-y-6">
		<!-- Profile card -->
		<div class="rounded-sm border border-brand-sand bg-white p-6 shadow-sm">
			<h2 class="mb-5 text-xs font-bold tracking-widest text-gray-400 uppercase">
				{m.profile_section_personal()}
			</h2>

			<div class="space-y-4">
				<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
					<label class="block">
						<span
							class="mb-1 block font-sans text-xs font-bold tracking-widest text-gray-400 uppercase"
						>
							{m.profile_label_first_name()}
						</span>
						<input
							type="text"
							name="firstName"
							value={data.editUser.firstName ?? ''}
							class="w-full rounded-sm border border-brand-sand px-3 py-2 font-serif text-sm focus:border-brand-navy focus:outline-none"
						/>
					</label>

					<label class="block">
						<span
							class="mb-1 block font-sans text-xs font-bold tracking-widest text-gray-400 uppercase"
						>
							{m.profile_label_last_name()}
						</span>
						<input
							type="text"
							name="lastName"
							value={data.editUser.lastName ?? ''}
							class="w-full rounded-sm border border-brand-sand px-3 py-2 font-serif text-sm focus:border-brand-navy focus:outline-none"
						/>
					</label>
				</div>

				<label class="block">
					<span
						class="mb-1 block font-sans text-xs font-bold tracking-widest text-gray-400 uppercase"
					>
						{m.profile_label_birth_date()}
					</span>
					<input
						type="text"
						placeholder="TT.MM.JJJJ"
						value={birthDateDisplay}
						oninput={handleBirthDateInput}
						class="w-full rounded-sm border border-brand-sand px-3 py-2 font-serif text-sm focus:border-brand-navy focus:outline-none"
					/>
					<input type="hidden" name="birthDate" value={birthDateIso} />
				</label>

				<label class="block">
					<span
						class="mb-1 block font-sans text-xs font-bold tracking-widest text-gray-400 uppercase"
					>
						{m.profile_label_email()}
					</span>
					<input
						type="email"
						name="email"
						value={data.editUser.email ?? ''}
						class="w-full rounded-sm border border-brand-sand px-3 py-2 font-serif text-sm focus:border-brand-navy focus:outline-none"
					/>
				</label>

				<label class="block">
					<span
						class="mb-1 block font-sans text-xs font-bold tracking-widest text-gray-400 uppercase"
					>
						{m.profile_label_contact()}
					</span>
					<textarea
						name="contact"
						rows="3"
						placeholder={m.profile_contact_placeholder()}
						class="w-full rounded-sm border border-brand-sand px-3 py-2 font-serif text-sm focus:border-brand-navy focus:outline-none"
						>{data.editUser.contact ?? ''}</textarea
					>
				</label>
			</div>
		</div>

		<!-- Groups card -->
		<div class="rounded-sm border border-brand-sand bg-white p-6 shadow-sm">
			<h2 class="mb-5 text-xs font-bold tracking-widest text-gray-400 uppercase">
				{m.admin_col_groups()}
			</h2>

			<div class="flex flex-wrap gap-3">
				{#each data.groups as group (group.id)}
					<label class="inline-flex items-center gap-2 text-sm text-gray-700">
						<input
							type="checkbox"
							name="groupIds"
							value={group.id}
							checked={data.editUser.groups?.some((g: { id: string }) => g.id === group.id)}
							class="rounded border-gray-300 text-brand-navy focus:ring-brand-mint"
						/>
						{group.name}
					</label>
				{/each}
			</div>
		</div>

		<!-- Password card -->
		<div class="rounded-sm border border-brand-sand bg-white p-6 shadow-sm">
			<h2 class="mb-5 text-xs font-bold tracking-widest text-gray-400 uppercase">
				{m.admin_label_new_password_optional()}
			</h2>

			<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
				<label class="block">
					<span
						class="mb-1 block font-sans text-xs font-bold tracking-widest text-gray-400 uppercase"
					>
						{m.profile_label_new_password()}
					</span>
					<input
						type="password"
						name="newPassword"
						class="w-full rounded-sm border border-brand-sand px-3 py-2 font-serif text-sm focus:border-brand-navy focus:outline-none"
					/>
				</label>

				<label class="block">
					<span
						class="mb-1 block font-sans text-xs font-bold tracking-widest text-gray-400 uppercase"
					>
						{m.profile_label_new_password_confirm()}
					</span>
					<input
						type="password"
						name="confirmPassword"
						class="w-full rounded-sm border border-brand-sand px-3 py-2 font-serif text-sm focus:border-brand-navy focus:outline-none"
					/>
				</label>
			</div>
		</div>

		<!-- Save bar -->
		<div
			class="sticky bottom-0 z-10 -mx-4 flex items-center justify-between border-t border-brand-sand bg-white px-6 py-4 shadow-[0_-2px_8px_rgba(0,0,0,0.06)]"
		>
			<a
				href="/admin"
				class="font-sans text-xs font-bold tracking-widest text-gray-500 uppercase hover:text-brand-navy"
			>
				{m.btn_cancel()}
			</a>
			<button
				type="submit"
				class="rounded-sm bg-brand-navy px-5 py-2 font-sans text-xs font-bold tracking-widest text-white uppercase transition-opacity hover:opacity-80"
			>
				{m.btn_save()}
			</button>
		</div>
	</form>
</div>
