<script lang="ts">
	import type { PageData } from './$types';

	import { Loader2 } from 'lucide-svelte';
	import { superForm } from 'sveltekit-superforms/client';

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

	import plausible from '$lib/stores/Plausible';
	import { addToast } from '$lib/components/Toaster.svelte';

	export let data: PageData;

	let submitting = false;

	const { form, errors, enhance } = superForm(data.form, {
		onSubmit() {
			submitting = true;
		},
		onResult({ result }) {
			if (result.type === 'success') {
				addToast({
					data: {
						title: 'Succès',
						description: 'Vos informations ont été mises à jour.'
					}
				});
			}

			submitting = false;
		}
	});

	$: optedOut = $plausible;
</script>

<form class="flex flex-col gap-4" method="POST" use:enhance>
	<label for="email">Email</label>
	<Input
		name="email"
		type="email"
		placeholder="philipzcwbarlow@peerat.dev"
		value={data.user?.email}
		disabled
	/>

	<label for="firstname">Prénom</label>
	<Input
		name="firstname"
		type="text"
		placeholder="Philip"
		aria-invalid={$errors.firstname ? 'true' : undefined}
		bind:value={$form.firstname}
	/>
	{#if $errors.firstname}
		<span class="text-sm text-red-500">{$errors.firstname}</span>
	{/if}

	<label for="lastname">Nom</label>
	<Input
		name="lastname"
		type="text"
		placeholder="Barlow"
		aria-invalid={$errors.lastname ? 'true' : undefined}
		bind:value={$form.lastname}
	/>
	{#if $errors.lastname}
		<span class="text-sm text-red-500">{$errors.lastname}</span>
	{/if}

	<label for="pseudo"> Nom d'utilisateur </label>
	<Input
		name="pseudo"
		type="text"
		placeholder="Cypher Wolf"
		aria-invalid={$errors.pseudo ? 'true' : undefined}
		bind:value={$form.pseudo}
	/>
	{#if $errors.pseudo}
		<span class="text-sm text-red-500">{$errors.pseudo}</span>
	{/if}

	<div class="flex items-center justify-between">
		<label for="optout"> Ne pas me tracer de manière anonyme </label>
		<input
			class="h-4 w-4"
			name="optout"
			type="checkbox"
			bind:value={optedOut}
			on:change={() => plausible.set(!optedOut)}
			checked={optedOut}
		/>
	</div>

	<p class="text-sm text-highlight-secondary">
		Nous utilisons Plausible pour analyser l'utilisation de notre site web de manière anonyme.
	</p>

	<Button variant="brand" disabled={submitting}>
		{#if submitting}
			<Loader2 class="mr-2 h-4 w-4 animate-spin" />
		{/if}
		Modifier
	</Button>
</form>
