<script lang="ts">
	import { type World } from '$gql/graphql';
	import { deleteWorlds, updateWorlds, type WorldInput } from '$gql/Mutations';
	import { itemEquals } from '$gql/Utils';
	import DeleteButton from '$lib/components/DeleteButton.svelte';
	import Dialog from '$lib/components/Dialog.svelte';
	import SubmitButton from '$lib/components/SubmitButton.svelte';
	import WorldForm from '$lib/forms/WorldForm.svelte';
	import { toastFinally } from '$lib/Toasts';
	import { confirmDeletion } from '$lib/Utils';
	import { getContextClient } from '@urql/svelte';
	import { closeModal } from 'svelte-modals';

	const client = getContextClient();

	export let isOpen: boolean;

	export let world: World;
	const original = structuredClone(world);
	$: pending = !itemEquals(original, world);

	function save(event: CustomEvent<WorldInput>) {
		updateWorlds(client, { ids: world.id, input: event.detail })
			.then(closeModal)
			.catch(toastFinally);
	}

	function deleteWorld() {
		confirmDeletion('World', world.name, () => {
			deleteWorlds(client, { ids: world.id }).then(closeModal).catch(toastFinally);
		});
	}
</script>

<Dialog {isOpen}>
	<svelte:fragment slot="header">
		<h2>Edit World</h2>
	</svelte:fragment>
	<WorldForm bind:world on:submit={save}>
		<div class="flex gap-4">
			<DeleteButton on:click={deleteWorld} />
			<div class="grow" />
			<SubmitButton active={pending} />
		</div>
	</WorldForm>
</Dialog>
