<script lang="ts">
	import { Button, Input, Label } from 'flowbite-svelte';
	import { CreateAreaTemplateStore } from '$houdini';

	let { scopeTemplateId, onadded }: { scopeTemplateId: string; onadded?: () => void } = $props();

	let name = $state('');
	let order = $state(0);
	let loading = $state(false);
	let error = $state('');

	const createArea = new CreateAreaTemplateStore();

	const handleSubmit = async (e: SubmitEvent) => {
		e.preventDefault();
		loading = true;
		error = '';
		try {
			const res = await createArea.mutate({ input: { name, order, scopeTemplateId } });
			if (res.errors?.length) {
				error = res.errors.map((e) => e.message).join(', ');
			} else {
				name = '';
				order = 0;
				onadded?.();
			}
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to add area';
		} finally {
			loading = false;
		}
	};
</script>

<form class="mb-4 flex flex-wrap items-end gap-3" onsubmit={handleSubmit}>
	<div>
		<Label for="areaName" class="mb-1">Name</Label>
		<Input id="areaName" bind:value={name} required />
	</div>
	<div>
		<Label for="areaOrder" class="mb-1">Order</Label>
		<Input id="areaOrder" type="number" bind:value={order} min={0} />
	</div>
	<Button type="submit" color="primary" disabled={loading}
		>{loading ? 'Adding…' : 'Add Area'}</Button
	>
	{#if error}
		<span class="text-xs text-red-600">{error}</span>
	{/if}
</form>
