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

	export let data: PageData;

	$: keyRoles = data.guild.roles.filter((r) =>
		data.guild.key_roles.some((id) => r.id === id),
	);

	$: options = data.guild.roles
		.filter((r) => !keyRoles.some((kr) => kr.id === r.id))
		.map((r) => ({ label: r.name, value: r.id }));

	let toAdd: string | null;

	const addRole = async () => {
		if (!toAdd) return;

		try {
			await fastFetch("PUT", `/api/guilds/${data.guild.id}/key-roles/${toAdd}`);
			const role = data.guild.roles.find((r) => r.id === toAdd);
			data.guild.key_roles.push(toAdd);
			data.guild = data.guild;
			addToast({
				header: "Added key role",
				body: `Added ${role?.name || `unknown role ${toAdd}`} to the list of key roles.`,
			});
			toAdd = null;
		} catch (e) {
			addToast({
				header: "Error adding key role",
				body:
					(e as ApiError).message || "Unknown error. Please try again later.",
			});
		}
	};

	const removeRole = async (id: string) => {
		try {
			await fastFetch("DELETE", `/api/guilds/${data.guild.id}/key-roles/${id}`);
			const role = data.guild.roles.find((r) => r.id === id);
			const idx = data.guild.key_roles.indexOf(id);
			if (idx > -1) data.guild.key_roles.splice(idx, 1);
			data.guild = data.guild;
			addToast({
				header: "Removed key role",
				body: `Removed ${role?.name || `unknown role ${toAdd}`} from the list of key roles.`,
			});
		} catch (e) {
			addToast({
				header: "Error removing key role",
				body:
					(e as ApiError).message || "Unknown error. Please try again later.",
			});
		}
	};
</script>

<h3>Key roles</h3>

<p>
	Key roles are logged separately from other roles, and also log <em>who</em> added
	or removed the role. Useful for moderator roles.
</p>

<div>
	<Label><strong>Add a new key role</strong></Label>
	<Svelecte
		bind:value={toAdd}
		{options}
		labelField="label"
		valueField="value"
		searchable={true}
	/>
</div>

<div class="my-2 d-grid d-md-block">
	<Button color="primary" on:click={() => addRole()} disabled={!toAdd}>
		Add key role
	</Button>
</div>

<div>
	<h4>Current key roles</h4>

	<ListGroup>
		{#each keyRoles as role (role.id)}
			<RoleListItem {role} on:click={() => removeRole(role.id)} />
		{/each}
	</ListGroup>
</div>
