<script lang="ts">
	import { enhance } from '$app/forms';

	type FormResult = {
		errors?: Record<string, string>;
		name?: string;
	} | null;

	let { form = null }: { form?: FormResult } = $props();

	let name = $state('');
	let touched = $state(false);
	let submitAttempted = $state(false);
	let formError = $state('');

	const isDisabled = $derived(name.trim().length === 0);
	const error = $derived(
		(touched || submitAttempted) && name.trim() === '' ? 'Haushaltsname ist erforderlich' : ''
	);

	$effect(() => {
		if (form?.errors) {
			formError = form.errors.form ?? '';
			name = form?.name ?? '';
		}
	});

	function handleSubmit(event: SubmitEvent) {
		submitAttempted = true;
		if (name.trim() === '') {
			event.preventDefault();
		}
	}

	function handleInput() {
		touched = true;
	}
</script>

<form method="POST" novalidate use:enhance onsubmit={handleSubmit}>
	<h1 class="mb-[8px] font-[var(--font-display)] text-[18px] font-medium md:text-[28px]">Haushalt benennen</h1>
	<p class="mb-[24px] text-[12px] text-[var(--color-text-muted)] md:text-[14px]">
		Gib deinem Haushalt einen Namen, damit du ihn leicht wiederfindest.
	</p>

	<div class="mb-[16px]">
		<label for="name" class="mb-[6px] block text-[14px] font-medium">Haushaltsname</label>
		<input
			type="text"
			id="name"
			name="name"
			placeholder="z.B. Familie Müller"
			autocomplete="organization"
			bind:value={name}
			oninput={handleInput}
			class="w-full rounded-[var(--radius-md)] border bg-[var(--color-page)] px-[12px] py-[10px] text-[14px] outline-none focus:ring-2 focus:ring-[var(--green-dark)] {error
				? 'border-[var(--color-error)]'
				: 'border-[var(--color-border)]'}"
		/>
		{#if error}
			<p class="mt-1 text-[12px] text-[var(--color-error)]">{error}</p>
		{/if}
	</div>

	{#if formError}
		<p
			class="mb-[16px] rounded-[var(--radius-md)] bg-[color-mix(in_srgb,var(--color-error),transparent_90%)] px-[12px] py-[10px] text-[12px] text-[var(--color-error)]"
		>
			{formError}
		</p>
	{/if}

	<button
		type="submit"
		disabled={isDisabled}
		class="w-full cursor-pointer rounded-[var(--radius-md)] bg-[var(--green-dark)] px-[24px] py-[12px] text-[14px] font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
	>
		Weiter → Vorräte einrichten
	</button>
</form>
