<script lang="ts">
	import { superForm } from 'sveltekit-superforms/client';
	import { afterUpdate } from 'svelte';
	import { writable } from 'svelte/store';
	import { RangeSlider, SlideToggle } from '@skeletonlabs/skeleton';
	import TextInput from './inputfields/TextInput.svelte';

	export let me;

	const { fields, validators } = $me.context;

	const initialFormData = fields.reduce((acc, field) => {
		acc[field.name] = field.placeholder;
		return acc;
	}, {});

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

	const successMessage = writable<string | null>(null);

	// Update the isValidated property of the store whenever the errors object changes
	$: {
		// Send events to the state machine based on the validation status
		if (!($errors.name || $errors.email || $errors.about || $errors.age || $errors.favoriteFood)) {
			$me.do.state.send('VALIDATE');
		} else {
			$me.do.state.send('INVALIDATE');
		}
	}

	async function handleSubmit() {
		// Manually validate the form
		const validationResult = await validate();

		// Prevent submission if there are errors
		if (!validationResult.valid) {
			return;
		}

		// Here, we'll just log the form data
		console.log(form);

		// Set the success message after successful submission
		successMessage.set('Form submitted successfully!');
	}

	function handleReset() {
		// Reset the form and remove the message
		form.set({});
		successMessage.set(null);
	}

	// After update, scroll to the message container for better user experience
	afterUpdate(() => {
		const messageContainer = document.getElementById('message-container');
		if (messageContainer) {
			messageContainer.scrollIntoView({ behavior: 'smooth' });
		}
	});
</script>

<div class="p-6">
	My ID is: {$me.id} <br />
	My state is: {$me.state}
</div>

<div class="flex items-center justify-center w-full h-full p-6">
	{#if $successMessage}
		<aside class="w-full max-w-md p-4 alert variant-ghost" id="message-container">
			<div class="alert-message">
				<h3 class="h3">Success</h3>
				<p>{$successMessage}</p>
			</div>
			<div class="alert-actions">
				<button
					class="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"
					on:click={handleReset}
				>
					Reset
				</button>
			</div>
		</aside>
	{:else}
		<form on:submit|preventDefault={handleSubmit} class="w-full max-w-md">
			{#each fields as field (field.name)}
				<div class="mb-4">
					{#if $errors[field.name]}
						<span class="block mb-2 font-semibold text-red-500">{$errors[field.name]}</span>
					{:else}
						<label for={field.name} class="block mb-2 font-semibold text-white"
							>{field.name.charAt(0).toUpperCase() + field.name.slice(1)}
						</label>
					{/if}
					{#if field.type === 'text' || field.type === 'email' || field.type === 'number'}
						<TextInput {form} {errors} {validate} {field} {constraints} />
					{:else if field.type === 'textarea'}
						<textarea
							name={field.name}
							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[field.name]}
							aria-invalid={$errors[field.name] ? 'true' : undefined}
							{...constraints[field.name]}
						/>
					{:else if field.type === 'select'}
						<select
							name={field.name}
							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[field.name]}
							aria-invalid={$errors[field.name] ? 'true' : undefined}
							{...constraints[field.name]}
						>
							<option value="">Select...</option>
							<option value="apple">Apple</option>
							<option value="banana">Banana</option>
							<option value="coconut">Coconut</option>
							<option value="strawberry">Strawberry</option>
							<option value="mango">Mango</option>
						</select>
					{:else if field.type === 'slider'}
						<RangeSlider
							name={field.name}
							bind:value={$form[field.name]}
							min={0}
							max={100}
							step={1}
							ticked
						>
							<div class="flex items-center justify-between">
								<div class="text-xs">{$form[field.name]} / 100</div>
							</div>
						</RangeSlider>
					{:else if field.type === 'toggle'}
						<SlideToggle name={field.name} bind:checked={$form[field.name]} />
					{/if}
				</div>
			{/each}
			<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={$me.state === 'notValidated'}
			>
				Submit
			</button>
		</form>
	{/if}
</div>
