<script lang="ts">
	import {
		Button,
		Label,
		ListGroup,
		ListGroupItem,
	} from "@sveltestrap/sveltestrap";
	import type { PageData } from "./$types";
	import { addToast } from "$lib/toast";
	import apiFetch, { fastFetch, TOKEN_KEY, type ApiError } from "$lib/api";
	import Svelecte from "svelecte";

	export let data: PageData;

	let toIgnore: string | null = null;
	const idRegex = /^\d{15,}$/;

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

		try {
			const user = await apiFetch<{ id: string; tag: string }>(
				"PUT",
				`/api/guilds/${data.guild.id}/ignored-users/${toIgnore}`,
			);
			data.users.push(user);
			data.users = data.users;
			addToast({
				header: "Ignored user",
				body: `Added ${user.tag} to the list of ignored users.`,
			});
			toIgnore = null;
		} catch (e) {
			addToast({
				header: "Error ignoring user",
				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-users/${id}`,
			);
			const user = data.users.find((u) => u.id === id);
			const idx = data.users.findIndex((u) => u.id === id);
			if (idx > -1) data.users.splice(idx, 1);
			data.users = data.users;
			addToast({
				header: "Stopped ignoring user",
				body: `Removed ${user?.tag || "unknown user " + id} from the list of ignored users.`,
			});
		} catch (e) {
			addToast({
				header: "Error removing user",
				body:
					(e as ApiError).message || "Unknown error. Please try again later.",
			});
		}
	};

	const fetchProps: RequestInit = {
		method: "GET",
		headers: {
			Authorization: localStorage.getItem(TOKEN_KEY) || "",
		},
	};
</script>

<h3>Ignored users</h3>

<p>Messages from ignored users will not be logged.</p>

<div>
	<Label><strong>Ignore a new user</strong></Label>
	<Svelecte
		bind:value={toIgnore}
		fetch="/api/guilds/{data.guild.id}/users?query=[query]"
		{fetchProps}
		multiple={false}
		searchable={true}
		creatable={true}
		labelField="name"
		valueField="id"
		creatablePrefix="user with ID "
	/>
	{#if toIgnore && !idRegex.test(toIgnore)}
		<p class="text-danger mt-2">
			If you're not ignoring a member of your server, you need to give a
			<strong>user ID</strong>, not their username.
		</p>
	{/if}
</div>

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

<h4>Currently ignored users</h4>

<ListGroup>
	{#each data.users as user (user.id)}
		<ListGroupItem class="d-flex justify-content-between align-items-center">
			<span>{user.tag} (ID: {user.id})</span>
			<Button color="link" on:click={() => removeIgnore(user.id)}>
				Stop ignoring
			</Button>
		</ListGroupItem>
	{/each}
</ListGroup>
