<script lang="ts">
	import { createDevice } from '$lib/api/device.remote';
	import * as Field from '$lib/components/ui/field/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import { toast } from 'svelte-sonner';

	interface Props {
		onSuccess?: () => void;
	}

	let { onSuccess }: Props = $props();
</script>

<form
	{...createDevice.enhance(async ({ form, submit }) => {
		try {
			await submit();

			const issues = createDevice.fields.allIssues();
			if (issues && issues.length > 0) {
				return;
			}

			const deviceName = createDevice.fields.name.value();

			form.reset();
			toast.success(`Device '${deviceName}' created`);
			onSuccess?.();
		} catch (error) {
			console.error('Failed to create device: ', error);
			toast.error('Failed to create device');
		}
	})}
	class="flex flex-col gap-3"
>
	<Field.Set>
		<Field.Group>
			<Field.Field>
				<Field.Label for="name">Device name</Field.Label>
				<Input {...createDevice.fields.name.as('text')} placeholder="e.g. Kindle Paperwhite" />
				{#each createDevice.fields.name.issues() ?? [] as issue}
					<Field.Error>{issue.message}</Field.Error>
				{/each}
			</Field.Field>
		</Field.Group>
	</Field.Set>

	<Button type="submit" class="ml-auto w-24">Create</Button>
</form>
