<script lang="ts">
	import { Button, Nav, NavItem, NavLink } from "@sveltestrap/sveltestrap";
	import type { LayoutData } from "./$types";
	import { page } from "$app/stores";
	import apiFetch, { type ApiError, type GuildConfig } from "$lib/api";
	import { addToast } from "$lib/toast";

	export let data: LayoutData;

	// This only saves log channels. All other pages are lists and are saved immediately upon adding/removing an entry.
	const save = async () => {
		try {
			const resp = await apiFetch<GuildConfig>(
				"PATCH",
				`/api/guilds/${data.guild.id}`,
				data.guild.config,
			);
			data.guild.config = resp;

			addToast({
				header: "Saved log channels.",
				body: "Successfully edited log channels and ignored channels.",
			});
		} catch (e) {
			addToast({
				header: "Error saving changes to log channels",
				body:
					(e as ApiError).message || "Unknown error. Please try again later.",
			});
		}
	};
</script>

<svelte:head>
	<title>Catalogger - Managing {data.guild.name}</title>
</svelte:head>

<div class="d-flex flex-column flex-lg-row justify-content-lg-between">
	<Nav pills={true} class="flex-column flex-lg-row mb-2">
		<NavLink href="#" disabled>Managing {data.guild.name}</NavLink>
		<NavLink
			href="/dash/{data.guild.id}"
			active={$page.url.pathname === `/dash/${data.guild.id}`}
		>
			Log channels
		</NavLink>
		<NavLink
			href="/dash/{data.guild.id}/redirects"
			active={$page.url.pathname === `/dash/${data.guild.id}/redirects`}
		>
			Redirects
		</NavLink>
		<NavLink
			href="/dash/{data.guild.id}/ignored-channels"
			active={$page.url.pathname === `/dash/${data.guild.id}/ignored-channels`}
		>
			Ignored channels
		</NavLink>
		<NavLink
			href="/dash/{data.guild.id}/ignored-users"
			active={$page.url.pathname === `/dash/${data.guild.id}/ignored-users`}
		>
			Ignored users
		</NavLink>
		<NavLink
			href="/dash/{data.guild.id}/key-roles"
			active={$page.url.pathname === `/dash/${data.guild.id}/key-roles`}
		>
			Key roles
		</NavLink>
		<NavLink
			href="/dash/{data.guild.id}/import"
			active={$page.url.pathname === `/dash/${data.guild.id}/import`}
		>
			Import/export settings
		</NavLink>
		<NavLink
			href="/dash/{data.guild.id}/delete"
			active={$page.url.pathname === `/dash/${data.guild.id}/delete`}
		>
			Delete all data
		</NavLink>
	</Nav>

	{#if $page.url.pathname === `/dash/${data.guild.id}`}
		<Button on:click={save} class="mb-2">Save changes</Button>
	{/if}
</div>

<slot />
