<script lang="ts">
	import { Button, Input, InputGroup } from "@sveltestrap/sveltestrap";
	import type { PageData } from "./$types";
	import apiFetch, { type ApiError } from "$lib/api";
	import { addToast } from "$lib/toast";
	import { goto } from "$app/navigation";
	import { saveAs } from "file-saver";

	export let data: PageData;

	let guildName: string = "";

	const deleteData = async () => {
		try {
			const backup = await apiFetch<any>(
				"POST",
				`/api/guilds/${data.guild.id}/leave`,
				{
					name: guildName,
				},
			);

			downloadBackup(backup);

			addToast({
				header: "Left server",
				body: `Successfully left ${data.guild.name} and deleted all data related to it.`,
			});

			await goto("/dash");
		} catch (e) {
			addToast({
				header: "Error leaving server",
				body: (e as ApiError).message || "Unknown error",
			});
		}
	};

	const downloadBackup = (data: any) => {
		const backup = JSON.stringify(data);
		const blob = new Blob([backup], { type: "text/plain;charset=utf-8" });
		saveAs(blob, "server-backup.json");
	};
</script>

<h3>Delete this server's data</h3>

<p>
	To make Catalogger leave your server and delete all data from your server,
	fill its name (<strong>{data.guild.name}</strong>) in below and press
	"Delete".
	<br />
	You will get a backup of your server's settings which you can restore later if
	you change your mind.
</p>

<p>
	<strong>
		Message data is not backed up. If you change your mind, we cannot restore it
		for you.
	</strong>
</p>

<p>
	<InputGroup>
		<Input type="text" placeholder="Server name" bind:value={guildName} />
		<Button
			color="danger"
			disabled={guildName !== data.guild.name}
			on:click={deleteData}
		>
			Delete
		</Button>
	</InputGroup>
</p>
