<script lang="ts">
	import { onDestroy, onMount } from 'svelte';
	import { derived } from 'svelte/store';
	import type { PageData } from './$types';

	import { cn } from '$lib/utils';

	import { createStateStore } from '$lib/stores/state';
	import { connectWebSocket } from '$lib/stores/websocket';

	import Button from '$lib/components/ui/button/button.svelte';

	export let data: PageData;

	type Log = {
		path: string;
		code: number;
		logged: boolean;
		type: string;
		pseudo?: string;
	};

	const stateStore = createStateStore<Log>();

	onMount(() => {
		connectWebSocket('/admin/logs', data.session, stateStore);
	});

	const logsStore = derived(stateStore, ($stateStore) =>
		$stateStore.requests.reduce(
			(acc, log) => {
				const key = log.pseudo || 'Unknown';
				if (!acc[key]) acc[key] = [];
				acc[key].unshift(log);
				return acc;
			},
			{} as Record<string, Log[]>
		)
	);

	let selectedUser = '';
	let logs: Record<string, Log[]> = {};

	const unsubscribe = logsStore.subscribe((value) => {
		logs = value;
	});

	const selectUser = (user: string) => {
		selectedUser = user;
	};

	onDestroy(unsubscribe);
</script>

<div class="flex h-full flex-col gap-4 lg:flex-row">
	<div class="overflow-auto lg:max-h-full lg:min-w-52">
		<ul class="flex gap-2 lg:flex-col">
			{#if !Object.keys(logs).length}
				<li>No logs</li>
			{/if}
			{#each Object.keys(logs) as user (user)}
				<li>
					<Button
						variant="outline"
						class={cn('w-full', {
							'bg-secondary': selectedUser === user
						})}
						on:click={() => selectUser(user)}
					>
						{user}
					</Button>
				</li>
			{/each}
		</ul>
	</div>
	{#if selectedUser && logs[selectedUser]}
		<div class="flex flex-1 flex-col overflow-auto">
			<main class="flex max-h-full flex-col gap-2">
				{#each logs[selectedUser] as log}
					<div class="rounded-lg border-border bg-card p-6 shadow-lg">
						<div class="flex items-center justify-between">
							<h5 class="text-xl font-semibold">{log.type}</h5>
							<span class="rounded-full px-3 py-1 text-sm">
								Code: {log.code}
							</span>
						</div>
						<div class="mt-4">
							<p class="text-sm font-medium text-muted-foreground">
								Path: <span class="font-normal text-foreground">{log.path}</span>
							</p>
							<p class="text-sm font-medium text-muted-foreground">
								Logged:
								<span
									class={cn({
										'text-green-500': log.logged,
										'text-red-500': !log.logged
									})}
								>
									{log.logged ? 'Yes' : 'No'}
								</span>
							</p>
							{#if log.pseudo}
								<p class="text-sm font-medium text-muted-foreground">
									Pseudo: <span class="font-normal text-foreground">{log.pseudo}</span>
								</p>
							{/if}
						</div>
					</div>
				{/each}
			</main>
		</div>
	{/if}
</div>
