<script lang="ts">
	import { goto } from '$app/navigation';

	import { fade } from 'svelte/transition';

	import { superForm } from 'sveltekit-superforms/client';
	import type { PageData, Snapshot } from './$types';

	import Button from '$lib/components/ui/Button.svelte';
	import Input from '$lib/components/ui/Input.svelte';

	export let data: PageData;

	const { form, errors, enhance } = superForm(data.form, {
		onResult({ result }) {
			switch (result.type) {
				case 'success':
					confirmation = true;
					break;
				case 'error':
					confirmation = false;
					break;
				case 'redirect':
					goto(result.location, {
						replaceState: true
					});
					break;
			}
		}
	});

	let confirmation = false;

	export const snapshot: Snapshot = {
		capture: () => confirmation,
		restore: (value) => (confirmation = value)
	};
</script>

<div class="flex h-screen w-full">
	<div class="flex w-full flex-col items-center justify-center">
		<div class="flex w-full max-w-xs flex-col gap-4">
			<h2 class="mx-auto text-xl font-bold">
				{confirmation ? 'Changer le mot de passe' : 'Mot de passe oublié'}
			</h2>
			<form class="flex flex-col justify-center gap-2" method="POST" action="?/forgot" use:enhance>
				<label for="email">Email</label>
				<Input
					bind:value={$form.email}
					name="email"
					type="email"
					placeholder="philipzcwbarlow@peerat.dev"
					autocomplete="off"
					required
				/>
				{#if $errors.email}<span class="text-sm text-red-500">{$errors.email}</span>{/if}

				{#if confirmation}
					<div
						class="flex flex-col gap-2"
						transition:fade={{
							duration: 300
						}}
					>
						<label for="passwd"> Mot de passe </label>
						<Input name="passwd" placeholder="************" type="password" />
						{#if $errors.passwd}<span class="text-sm text-red-500">{$errors.passwd}</span>{/if}

						<label for="code"> Code </label>
						<Input name="code" placeholder="1234" type="text" />
						{#if $errors.code}<span class="text-sm text-red-500">{$errors.code}</span>{/if}
					</div>
				{/if}

				<Button class="mt-2" variant="brand">
					<!-- {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} -->
					{confirmation ? 'Modifier' : 'Envoyer le mail'}
				</Button>

				<ul class="flex justify-between">
					<li>
						<a class="text-highlight-secondary hover:text-brand" href="/sign-in">Se connecter</a>
					</li>
					{#if confirmation}
						<li>
							<button formaction="?/register" class="text-highlight-secondary hover:text-brand"
								>Pas reçu ?</button
							>
						</li>
					{/if}
				</ul>
			</form>
		</div>
	</div>
</div>
