<script lang="ts">
	import { createMachine, assign } from 'xstate';
	import { useMachine } from '@xstate/svelte';
	import { superForm } from 'sveltekit-superforms/client';
	import { TreeSchema } from '$lib/types/TreeSchema';
	import { writable, get } from 'svelte/store';
	import { createUser } from './userService';
	import { derived } from 'svelte/store';
	import Composer from '$lib/core/refactor/Composer.svelte';

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

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

	export const snapshot = { capture, restore };

	const isFormValid = writable(false); // Store to keep track of form validation status

	async function handleSubmit() {
		const validationResult = await validate();
		if (!validationResult.valid) {
			return;
		}
		console.log(form);
		isFormValid.set(true); // Set the form validation status to true after successful validation
	}

	const stateMachine = createMachine(
		{
			id: 'steps',
			initial: 'start',
			context: {
				name: '',
				email: '',
				constraints: {}
			},
			states: {
				start: {
					meta: {
						title: 'Welcome!',
						description: 'Start your registration process by clicking next.',
						buttonLabel: 'Start'
					},
					on: { NEXT: 'name' }
				},
				name: {
					meta: {
						title: 'Name Input',
						description: 'Please enter your name.',
						fieldLabel: 'Name',
						buttonLabel: 'Next'
					},
					entry: assign({
						constraints: (context) => constraints.name || {}
					}),
					on: {
						NEXT: {
							target: 'email',
							actions: ['setName']
						},
						BACK: 'start'
					}
				},
				email: {
					meta: {
						title: 'Email Input',
						description: 'Please enter your email address.',
						fieldLabel: 'Email',
						buttonLabel: 'Next'
					},
					entry: assign({
						constraints: (context) => constraints.email || {}
					}),
					on: {
						NEXT: {
							target: 'litStatus',
							actions: ['setEmail']
						},
						BACK: 'name'
					}
				},
				litStatus: {
					meta: {
						title: 'LitStatus',
						buttonLabel: 'next',
						composer: {
							id: 'litStatus',
							component: 'LitStatus'
						}
					},
					on: {
						NEXT: 'summary',
						BACK: 'email'
					}
				},
				summary: {
					meta: {
						title: 'Summary',
						description: 'Review your details before submission.',
						buttonLabel: 'test'
					},
					on: {
						SUBMIT: 'submitting',
						BACK: 'litStatus'
					}
				},
				submitting: {
					meta: {
						title: 'Submitting...'
					},
					invoke: {
						src: 'createUserService',
						onDone: 'success',
						onError: {
							target: 'failure',
							actions: assign({
								error: (context, event) => event.data
							})
						}
					}
				},
				success: {
					meta: {
						title: 'Success',
						buttonLabel: 'Start again'
					},
					on: {
						RESTART: 'start'
					}
				},
				failure: {
					meta: {
						title: 'Submission Failed',
						buttonLabel: 'Restart'
					},
					on: {
						RESTART: 'start'
					}
				}
			}
		},
		{
			actions: {
				setName: assign({
					name: (context, event) => $form.name
				}),
				setEmail: assign({
					email: (context, event) => $form.email
				})
			},
			services: {
				createUserService: (context) => {
					console.log('Attempting to create user...');
					return createUser(context.name, context.email);
				}
			}
		}
	);

	const { state, send } = useMachine(stateMachine);

	$: {
		isFormValid.set(Object.keys(get(errors)).length === 0);
	}

	const possibleActions = derived(state, ($state) =>
		Object.keys(stateMachine.states[$state.value]?.on || {})
	);
</script>

<main class="flex items-center justify-center w-full h-full">
	<div class="w-full max-w-lg">
		<h1 class="text-2xl">
			{$state.value in stateMachine.states && stateMachine.states[$state.value].meta
				? stateMachine.states[$state.value].meta.title
				: 'Unknown state'}
		</h1>
		<p>
			{$state.value in stateMachine.states
				? stateMachine.states[$state.value].meta.description
				: ''}
		</p>

		{#if stateMachine.states[$state.value].meta.composite}
			<Composer composer={stateMachine.states[$state.value].meta.composer} />
		{/if}

		{#if $state.value === 'start'}Welcome{:else if $state.value === 'name'}
			<form on:submit|preventDefault={handleSubmit} class="w-full max-w-lg">
				<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"
							>{$state.value in stateMachine.states
								? stateMachine.states[$state.value].meta.fieldLabel
								: ''}</label
						>
					{/if}

					<input
						name={$state.value}
						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}
						{...$state.context.constraints}
					/>
				</div>
			</form>
		{:else if $state.value === 'email'}
			<form on:submit|preventDefault={handleSubmit} class="w-full max-w-lg">
				<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"
							>{$state.value in stateMachine.states
								? stateMachine.states[$state.value].meta.fieldLabel
								: ''}</label
						>
					{/if}

					<input
						name={$state.value}
						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}
						{...$state.context.constraints}
					/>
				</div>
			</form>
		{:else if $state.value === 'summary'}
			<p>Name: {$form.name}</p>
			<p>Email: {$form.email}</p>
		{:else if $state.value === 'submitting'}
			Add spinner here
		{:else if $state.value === 'success'}
			<p>Thank you for your submission!</p>
		{:else if $state.value === 'failure'}
			<p class="text-red-500">
				Error: {$state.context.error?.message || 'An unknown error occurred.'}
			</p>
		{/if}
		{#if possibleActions}
			<div class="flex justify-between">
				{#each $possibleActions as action (action)}
					{#if action === 'BACK'}
						<button
							class="px-4 py-2 mt-4 text-white bg-blue-500 rounded"
							on:click={() => send(action)}
						>
							{action}
						</button>
					{/if}
				{/each}

				{#each $possibleActions as action (action)}
					{#if action !== 'NEXT' && action !== 'BACK'}
						<button
							class="px-4 py-2 mx-auto mt-4 text-white bg-blue-500 rounded"
							on:click={() => send(action)}
						>
							{action}
						</button>
					{/if}
				{/each}

				{#each $possibleActions as action (action)}
					{#if action === 'NEXT'}
						<button
							class="px-4 py-2 mt-4 text-white bg-blue-500 rounded"
							on:click={() => send(action)}
							disabled={$errors[$state.value] || $state.context.constraints[$state.value]}
						>
							{$state.value in stateMachine.states
								? stateMachine.states[$state.value].meta.buttonLabel
								: ''}
						</button>
					{/if}
				{/each}
			</div>
		{/if}
	</div>
</main>
