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

	import Loader from 'lucide-svelte/icons/loader-circle';
	import { zodClient } from 'sveltekit-superforms/adapters';
	import { superForm } from 'sveltekit-superforms/client';

	import * as Form from '$lib/components/ui/form';
	import Input from '$lib/components/ui/input/input.svelte';

	import Textarea from '$lib/components/ui/textarea/textarea.svelte';
	import { formSchema } from './schema';
	import Button from '$lib/components/ui/button/button.svelte';

	export let data: PageData;

	const form = superForm(data.form, {
		validators: zodClient(formSchema),
		delayMs: 500,
		multipleSubmits: 'prevent'
	});

	const { form: formData, enhance, delayed } = form;
</script>

<section>
	<form class="flex flex-col gap-2" method="POST" use:enhance>
		<div class="flex items-center justify-between">
			<h2 class="text-xl font-bold">Modifier le puzzle</h2>
			<div class="flex gap-2">
				{#if $formData.chapter}
					<Button href="/chapters/{$formData.chapter}/puzzle/{data.puzzle.id}">
						Voir le puzzle
					</Button>
				{/if}
				<Form.Button disabled={$delayed}>
					{#if $delayed}
						<Loader class="mr-2 h-4 w-4 animate-spin" />
					{/if}
					Modifier
				</Form.Button>
			</div>
		</div>
		<Form.Field {form} name="name">
			<Form.Control let:attrs>
				<Form.Label>Nom</Form.Label>
				<Input {...attrs} bind:value={$formData.name} placeholder="Philip" />
			</Form.Control>
			<Form.FieldErrors />
		</Form.Field>
		<Form.Field {form} name="content">
			<Form.Control let:attrs>
				<Form.Label>Contenu</Form.Label>
				<Textarea {...attrs} bind:value={$formData.content} placeholder="Barlow" />
			</Form.Control>
			<Form.FieldErrors />
		</Form.Field>
		<Form.Field {form} name="soluce">
			<Form.Control let:attrs>
				<Form.Label>Solution</Form.Label>
				<Input {...attrs} bind:value={$formData.soluce} placeholder="Cypherwolf" />
			</Form.Control>
			<Form.FieldErrors />
		</Form.Field>
		<Form.Field {form} name="score_max">
			<Form.Control let:attrs>
				<Form.Label>Score maximum</Form.Label>
				<Input type="number" {...attrs} bind:value={$formData.score_max} placeholder="Cypherwolf" />
			</Form.Control>
			<Form.FieldErrors />
		</Form.Field>
		<Form.Field {form} name="chapter">
			<Form.Control let:attrs>
				<Form.Label>Chapitre</Form.Label>
				<Input type="number" {...attrs} bind:value={$formData.chapter} placeholder="Cypherwolf" />
			</Form.Control>
			<Form.FieldErrors />
		</Form.Field>
	</form>
</section>
