<script lang="ts">
	let { event = $bindable(), readonly = false } = $props();

	let loading = $state(false);
	let showForm = $derived((!event.name || !event.date) && !readonly);

	function handleSubmit(e: Event) {
		e.preventDefault();
		loading = true;
		const form = e.target as HTMLFormElement;
		const formData = new FormData(form);
		event = {
			name: formData.get('name'),
			date: formData.get('date')
		};
		showForm = false;
		loading = false;
	}

	function showEditForm() {
		if (!readonly) {
			showForm = true;
		}
	}
</script>

{#if showForm}
	<form
		onsubmit={handleSubmit}
		autocomplete="off"
		class="flex w-full flex-col space-y-4 rounded border border-gray-300 bg-white p-8 shadow-none"
	>
		<h2 class="mb-4 text-center text-2xl font-semibold">Create Event</h2>
		<label class="mt-2 flex flex-col text-gray-700">
			Name
			<input
				type="text"
				name="name"
				class="mt-1 rounded border border-gray-300 px-3 py-2 focus:ring-2 focus:ring-blue-200 focus:outline-none"
				required
				value={event.name ?? ''}
			/>
		</label>
		<label class="mt-2 flex flex-col text-gray-700">
			Date
			<input
				type="date"
				name="date"
				class="mt-1 rounded border border-gray-300 px-3 py-2 focus:ring-2 focus:ring-blue-200 focus:outline-none"
				required
				value={event.date ?? ''}
			/>
		</label>
		<button
			type="submit"
			class="mt-4 w-full rounded bg-blue-600 py-2 text-white transition hover:bg-blue-700"
		>
			Save
		</button>
	</form>
{/if}

{#if !showForm}
	{#if !readonly}
		<button
			class="mb-4 w-full rounded bg-blue-600 py-2 text-white transition hover:bg-blue-700"
			onclick={showEditForm}
			aria-label="Edit event"
		>
			Edit the event
		</button>
	{/if}
	<div class="rounded border border-gray-300 bg-white p-4">
		<h2 class="mb-2 text-xl font-bold">Event Preview</h2>
		{#if Object.keys(event).length > 0}
			<ul>
				<li><span class="font-semibold">{event.name}</span></li>
				<li class="text-gray-700">{event.date}</li>
			</ul>
		{:else}
			<strong class="text-gray-700">No event created yet...</strong>
		{/if}
	</div>
{/if}
