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

	export let data: PageData;

	$: ignored = data.guild.config.ignored_channels;
	$: options = makeFullOptions(data.guild, ignored);

	$: 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})`;

	let toIgnore: string | null = null;

	const addIgnore = async () => {
		if (!toIgnore) return;

		try {
			await fastFetch(
				"PUT",
				`/api/guilds/${data.guild.id}/ignored-channels/${toIgnore}`,
			);
			ignored.push(toIgnore);
			ignored = ignored;
			addToast({
				header: "Ignored channel",
				body: `Added ${channelName(toIgnore)} to the list of ignored channels.`,
			});
			toIgnore = null;
		} catch (e) {
			addToast({
				header: "Error ignoring channel",
				body:
					(e as ApiError).message || "Unknown error. Please try again later.",
			});
		}
	};

	const removeIgnore = async (id: string) => {
		try {
			await fastFetch(
				"DELETE",
				`/api/guilds/${data.guild.id}/ignored-channels/${id}`,
			);
			const idx = ignored.indexOf(id);
			if (idx > -1) ignored.splice(idx, 1);
			ignored = ignored;
			addToast({
				header: "Stopped ignoring channel",
				body: `Removed ${channelName(id)} from the list of ignored channels.`,
			});
		} catch (e) {
			addToast({
				header: "Error removing channel",
				body:
					(e as ApiError).message || "Unknown error. Please try again later.",
			});
		}
	};
</script>

<h3>Ignored channels</h3>

<p>
	Messages from ignored channels will not be logged. Note that this does not
	ignore channel update events, any changes to the channel will still be logged.
</p>

<div>
	<Label><strong>Ignore a new channel</strong></Label>
	<ChannelSelect bind:value={toIgnore} {options} />
</div>

<div class="my-2 d-grid d-md-block">
	<Button color="primary" on:click={() => addIgnore()} disabled={!toIgnore}>
		Ignore channel
	</Button>
</div>

<div>
	<h4>Currently ignored channels</h4>
</div>

<ListGroup>
	{#each ignored as id}
		<ListGroupItem class="d-flex justify-content-between align-items-center">
			{channelName(id)}
			<Button color="link" on:click={() => removeIgnore(id)}>
				Stop ignoring
			</Button>
		</ListGroupItem>
	{/each}
</ListGroup>
