<script lang="ts">
	import { updateTags } from '$gql/Mutations';
	import { namespaceList } from '$gql/Queries';
	import { toastFinally } from '$lib/Toasts';
	import { UpdateTagsControls } from '$lib/Update';
	import Dialog from '$lib/components/Dialog.svelte';
	import LabelledBlock from '$lib/components/LabelledBlock.svelte';
	import Select from '$lib/components/Select.svelte';
	import SubmitButton from '$lib/components/SubmitButton.svelte';
	import { getContextClient } from '@urql/svelte';
	import { closeModal } from 'svelte-modals';
	import UpdateModeSelector from './components/UpdateModeSelector.svelte';

	const client = getContextClient();

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

	export let isOpen: boolean;
	export let ids: number[];

	const controls = new UpdateTagsControls();

	const update = () => {
		updateTags(client, { ids: ids, input: controls.toInput() })
			.then(closeModal)
			.catch(toastFinally);
	};
</script>

<Dialog {isOpen}>
	<svelte:fragment slot="header">
		<h2>Edit Tags</h2>
	</svelte:fragment>
	<form on:submit|preventDefault={update}>
		<LabelledBlock label="Namespaces" let:id>
			<Select multi {id} options={namespaces} bind:value={controls.namespaces.ids} />
			<UpdateModeSelector bind:mode={controls.namespaces.options.mode} slot="controls" />
		</LabelledBlock>

		<div class="flex justify-end gap-4">
			<SubmitButton active={controls.hasInput()} />
		</div>
	</form>
</Dialog>
