<script lang="ts">
	import type { ApiError } from "$lib/api";
	import { Button, Label, ListGroup } from "@sveltestrap/sveltestrap";
	import type { PageData } from "./$types";
	import ChannelSelect from "../ChannelSelect.svelte";
	import { fastFetch } from "$lib/api";
	import { addToast } from "$lib/toast";
	import { makeFullOptions } from "$lib/util";
	import RemovableListItem from "$lib/components/RemovableListItem.svelte";

	export let data: PageData;

	$: redirects = data.guild.channels.redirects;

	$: allChannels = [
		...data.guild.channels_without_category.map((c) => ({
			id: c.id,
			name: `#${c.name}`,
		})),
		...data.guild.categories.map((cat) => ({ id: cat.id, name: cat.name })),
		...data.guild.categories.flatMap((cat) =>
			cat.channels.map((c) => ({ id: c.id, name: `#${c.name}` })),
		),
	];

	const channelName = (id: string) =>
		allChannels.find((c) => c.id === id)?.name || `(unknown channel ${id})`;

	$: sourceOptions = makeFullOptions(data.guild, Object.keys(redirects));
	$: targetOptions = data.options;

	let source: string | null = null;
	let target: string | null = null;

	const addRedirect = async () => {
		if (!source || !target) {
			addToast({
				header: "Can't add redirect",
				body: "You haven't selected a source and target channel.",
			});
			return;
		}

		try {
			await fastFetch("POST", `/api/guilds/${data.guild.id}/redirects`, {
				source,
				target,
			});

			data.guild.channels.redirects[source] = target;

			addToast({ body: "Successfully added redirect." });
		} catch (e) {
			addToast({
				header: "Error adding redirect",
				body:
					(e as ApiError).message || "Unknown error. Please try again later.",
			});
		}
	};

	const removeRedirect = async (id: string) => {
		try {
			await fastFetch("DELETE", `/api/guilds/${data.guild.id}/redirects/${id}`);

			delete data.guild.channels.redirects[id];
			data.guild.channels.redirects = data.guild.channels.redirects;

			addToast({ body: "Successfully removed redirect." });
		} catch (e) {
			addToast({
				header: "Error removing redirect",
				body:
					(e as ApiError).message || "Unknown error. Please try again later.",
			});
		}
	};
</script>

<h3>Add new redirect</h3>

<div class="row">
	<div class="col-sm">
		<Label><strong>Source</strong></Label>
		<ChannelSelect bind:value={source} options={sourceOptions} />
	</div>

	<div class="col-sm">
		<Label><strong>Target</strong></Label>
		<ChannelSelect bind:value={target} options={targetOptions} />
	</div>
</div>

<div class="my-2 d-grid d-md-block">
	<Button
		color="primary"
		disabled={!source || !target}
		on:click={() => addRedirect()}>Add redirect</Button
	>
</div>

{#if Object.keys(redirects).length > 0}
	<h3>Existing redirects</h3>

	<ListGroup>
		{#each Object.keys(redirects) as redirectSource}
			<RemovableListItem
				on:click={() => removeRedirect(redirectSource)}
				buttonText="Remove redirect"
			>
				{channelName(redirectSource)} ➜ {channelName(redirects[redirectSource])}
			</RemovableListItem>
		{/each}
	</ListGroup>
{:else}
	<p>There are no redirects configured.</p>
{/if}
