<script>
	import { applyAction, enhance } from '$app/forms';
	import { page } from '$app/state';
	import { receive, send } from '$lib/utils/helpers';

	import { t } from 'svelte-i18n';
	import InputField from '$lib/components/InputField.svelte';
	import { onMount } from 'svelte';

	let password = '',
		confirm_password = '';

	/** @type{string | null} */
	let token = null;

	onMount(() => {
		token = page.url.searchParams.get('token');
		console.log(token);
		if (!token) {
			form ||= { errors: [] }; // Ensure form exists with an errors array
			form.errors.push({
				field: 'server.general',
				key: 'server.error.no_auth_token',
				id: Math.random() * 1000
			});
		}
	});

	/** @type {import('./$types').ActionData} */
	export let form;

	/** @type {import('./$types').SubmitFunction} */
	const handleChange = async () => {
		return async ({ result }) => {
			await applyAction(result);
		};
	};
</script>

<div class="container">
	<form class="content" method="POST" use:enhance={handleChange}>
		<h1 class="step-title title">{$t('change_password')}</h1>
		{#if form?.errors}
			{#each form.errors as error (error.id)}
				<h4
					class="step-subtitle warning"
					in:receive={{ key: error.id }}
					out:send={{ key: error.id }}
				>
					{$t(error.key, {
						values: {
							message:
								error.field
									.split(' ')
									.map((tag) => $t(tag))
									.join(', ') || ''
						}
					})}
				</h4>
			{/each}
		{/if}

		<input type="hidden" name="user_id" value={page.params.id} />
		<input type="hidden" name="token" value={token} />
		<InputField
			name="user[password]"
			type="password"
			label={$t('password')}
			placeholder={$t('placeholder.password')}
			bind:value={password}
			otherPasswordValue={confirm_password}
		/>
		<InputField
			name="confirm_password"
			type="password"
			label={$t('confirm_password')}
			placeholder={$t('placeholder.password')}
			bind:value={confirm_password}
			otherPasswordValue={password}
		/>

		<button class="button-dark">{$t('change_password')} </button>
	</form>
</div>
