<script lang="ts">
	import { page } from '$app/stores';
	import { env } from '$env/dynamic/public';
	import { ArrowLeftOnRectangle, Cog6Tooth, Flag, UserGroup, Users } from 'svelte-heros-v2';
	import { buttonTriggeredRequest } from '$lib/components/utils';
	import { goto } from '$app/navigation';
	import type { LayoutData } from './$types';
	import { adminCount, errorMessage, reportCount } from '$lib/stores';
	import ErrorToast from '$lib/components/Toast/ErrorToast.svelte';

	async function logout() {
		const response = await fetch(`${env.PUBLIC_BASE_PATH}/admin/logout`, {
			method: 'POST'
		});
		if (response.ok) {
			await goto(`${env.PUBLIC_BASE_PATH}/`);
		} else {
			throw new Error();
		}
	}

	export let data: LayoutData;
	if (data.reportCount) $reportCount = data.reportCount;
	if (data.adminCount) $adminCount = data.adminCount;

	let tabs = [
		{
			path: `${env.PUBLIC_BASE_PATH}/admin/users`,
			icon: UserGroup,
			name: 'Registrierte Nutzer',
			badge: data.userCount,
			enabled: data.userCount != null
		},
		{
			path: `${env.PUBLIC_BASE_PATH}/admin/reports`,
			icon: Flag,
			name: 'Reports',
			badge: $reportCount,
			enabled: data.reportCount != null
		},
		{
			path: `${env.PUBLIC_BASE_PATH}/admin/admin`,
			icon: Users,
			name: 'Website Admins',
			badge: $adminCount,
			enabled: data.adminCount != null
		},
		{
			path: `${env.PUBLIC_BASE_PATH}/admin/settings`,
			icon: Cog6Tooth,
			name: 'Website Einstellungen',
			badge: null,
			enabled: data.settingsRead
		}
	];

	let pageTitleSuffix =
		(tabs.find((t) => $page.url.pathname === t.path)?.name ??
		$page.url.pathname === `${env.PUBLIC_BASE_PATH}/admin/login`)
			? 'Login '
			: null;
</script>

<svelte:head>
	<title>Craftattack Admin{pageTitleSuffix ? ` - ${pageTitleSuffix}` : ''}</title>
</svelte:head>

{#if $page.url.pathname !== `${env.PUBLIC_BASE_PATH}/admin/login`}
	<div class="h-12 relative bg-base-200 flex justify-center items-center">
		<ul class="menu menu-horizontal h-10 p-0 flex items-center bg-base-300 rounded-lg">
			{#each tabs as tab}
				{#if tab.enabled}
					<li>
						<a href={tab.path}>
							<svelte:component this={tab.icon} />
							<span class="mr-1" class:underline={$page.url.pathname === tab.path}>{tab.name}</span>
							{#if tab.badge != null}
								<div class="badge">{tab.badge}</div>
							{/if}
						</a>
					</li>
				{/if}
			{/each}
		</ul>
		<div class="absolute top-0 right-0 flex items-center h-full">
			<ul class="menu menu-vertical">
				<li>
					<button on:click={(e) => buttonTriggeredRequest(e, logout())}>
						<ArrowLeftOnRectangle />
						<span>Ausloggen</span>
					</button>
				</li>
			</ul>
		</div>
	</div>
	<div class="h-full w-full -mt-12 pt-12 overflow-y-scroll overflow-x-hidden">
		<slot />
	</div>
{:else}
	<div class="h-full w-full">
		<slot />
	</div>
{/if}

{#if $errorMessage}
	<ErrorToast timeout={2000} show={$errorMessage != null}>
		<span>{$errorMessage}</span>
	</ErrorToast>
{/if}
