<script lang="ts">
	import type { TagInput } from '$gql/Mutations';
	import { namespaceList } from '$gql/Queries';
	import type { OmitIdentifiers } from '$gql/Utils';
	import type { FullTag } from '$gql/graphql';
	import Labelled from '$lib/components/Labelled.svelte';
	import Select from '$lib/components/Select.svelte';
	import { getContextClient } from '@urql/svelte';
	import { createEventDispatcher } from 'svelte';

	const client = getContextClient();
	const dispatch = createEventDispatcher<{ submit: TagInput }>();

	export let tag: OmitIdentifiers<FullTag>;

	$: namespaceQuery = namespaceList(client);
	$: namespaces = $namespaceQuery.data?.namespaces.edges;

	function submit() {
		dispatch('submit', {
			name: tag.name,
			description: tag.description,
			namespaces: { ids: tag.namespaces.map((n) => n.id) }
		});
	}
</script>

<form on:submit|preventDefault={submit}>
	<div class="grid-labels">
		<Labelled label="Name" let:id>
			<!-- svelte-ignore a11y-autofocus -->
			<input autofocus required {id} bind:value={tag.name} />
		</Labelled>
		<Labelled label="Description" let:id>
			<textarea rows={3} {id} bind:value={tag.description} />
		</Labelled>
		<Labelled label="Namespaces" let:id>
			<Select multi object {id} options={namespaces} bind:value={tag.namespaces} />
		</Labelled>
	</div>
	<slot />
</form>
