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

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

	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() {
		showForm = true;
	}
</script>

{#if showForm}
	<form
		on:submit={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}
	<button
		class="mb-4 w-full rounded bg-blue-600 py-2 text-white transition hover:bg-blue-700"
		on:click={showEditForm}
		aria-label="Edit event"
	>
		Edit the event
	</button>
{/if}

{#if !showForm}
	<div
		class="rounded border-l-4 border-green-500 p-4 text-green-700"
		class:bg-gray-100={loading}
		class:bg-green-100={!loading}
	>
		{#if loading}
			<strong class="text-gray-700">Loading...</strong>
		{:else if Object.keys(event).length > 0}
			<ol>
				<li><strong>{event.name}</strong></li>
				<li>{event.date}</li>
			</ol>
		{:else}
			<strong class="text-gray-700">No event created yet...</strong>
		{/if}
	</div>
{/if}
