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

	let showForm = $derived(!email.subject || !email.body);

	function handleSubmit(e: Event) {
		e.preventDefault();
		const form = e.target as HTMLFormElement;
		const formData = new FormData(form);
		email = {
			subject: formData.get('subject') as string,
			body: formData.get('body') as string
		};
		showForm = false;
	}

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

{#if showForm}
	<form on:submit={handleSubmit} class="flex flex-col space-y-4 bg-white p-8 rounded border border-gray-300 w-full shadow-none">
		<h2 class="text-2xl font-semibold text-center mb-4">Craft Email</h2>
		<label class="flex flex-col text-gray-700">
			Subject
			<input
				type="text"
				name="subject"
				value={email.subject ?? ''}
				class="mt-1 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-200"
				required
			/>
		</label>
		<label class="flex flex-col text-gray-700">
			Body
			<textarea
				name="body"
				value={email.body ?? ''}
				class="mt-1 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-200 resize-none"
				rows="6"
				required
			></textarea>
		</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>
{:else}
	<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 email"
	>
		Edit email
	</button>
	<div class="rounded border-l-4 border-green-500 p-4 text-green-700 bg-green-100">
		<ol>
			<li><strong>{email.subject}</strong></li>
			<li class="whitespace-pre-line">{email.body}</li>
		</ol>
	</div>
{/if}