<script lang="ts">
	import { superForm } from 'sveltekit-superforms/client';
	import { UserSchema } from '$lib/types/UserSchema';
	import currentStep from './Recipies.svelte';

	const initialFormData = { name: '', email: '' };

	const { form, errors, validate, constraints } = superForm(initialFormData, {
		validators: UserSchema,
		warnings: {
			noValidationAndConstraints: false
		},
		validationMethod: 'oninput',
		clearOnSubmit: 'errors-and-message'
	});

	async function handleSubmit() {
		const validationResult = await validate();

		if (validationResult.valid) {
			console.log(form);
			currentStep.update((val) => val + 1); // move to the next step
		}
	}
</script>

<form on:submit|preventDefault={handleSubmit} class="w-full max-w-md">
	<div class="mb-4">
		{#if $errors.name}
			<span class="block mb-2 font-semibold text-red-500">{$errors.name}</span>
		{:else}
			<label for="name" class="block mb-2 font-semibold text-white">Name</label>
		{/if}

		<input
			name="name"
			type="text"
			class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
			bind:value={$form.name}
			aria-invalid={$errors.name ? 'true' : undefined}
			{...constraints.name}
		/>
	</div>

	<div class="mb-4">
		{#if $errors.email}
			<span class="block mb-2 font-semibold text-red-500">{$errors.email}</span>
		{:else}
			<label for="email" class="block mb-2 font-semibold text-white">Email</label>
		{/if}

		<input
			name="email"
			type="email"
			class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
			bind:value={$form.email}
			aria-invalid={$errors.email ? 'true' : undefined}
			{...constraints.email}
		/>
	</div>

	<button
		type="submit"
		class="w-full px-4 py-2 mt-4 text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
		disabled={$errors.name || $errors.email}
	>
		Submit
	</button>
</form>
