<script lang="ts">
	import { deleteCircles, updateCircles } from '$gql/Mutations';
	import { omitIdentifiers } from '$gql/Utils';
	import type { Circle, UpdateCircleInput } from '$gql/graphql';
	import { toastFinally } from '$lib/Toasts';
	import { confirmDeletion } from '$lib/Utils';
	import DeleteButton from '$lib/components/DeleteButton.svelte';
	import Dialog from '$lib/components/Dialog.svelte';
	import CircleForm from '$lib/forms/CircleForm.svelte';
	import { getContextClient } from '@urql/svelte';
	import type { ModalProps } from 'svelte-modals';

	const client = getContextClient();

	interface Props extends ModalProps {
		circle: Circle;
	}

	let { circle, ...modal }: Props = $props();
	const initial = omitIdentifiers(circle);

	function submit(input: UpdateCircleInput) {
		updateCircles(client, { ids: circle.id, input }).then(modal.close).catch(toastFinally);
	}

	function deleteCircle() {
		confirmDeletion('Circle', circle.name, () => {
			deleteCircles(client, { ids: circle.id }).then(modal.close).catch(toastFinally);
		});
	}
</script>

<Dialog title="Edit Circle" {...modal}>
	<CircleForm {initial} {submit}>
		<DeleteButton onclick={deleteCircle} />
	</CircleForm>
</Dialog>
