<script lang="ts">
	import * as Table from "$lib/components/ui/table";
	import { eventTarget } from "$lib/ws.svelte";
	import { TicketCheckIcon, TicketIcon, TicketSlashIcon, TicketXIcon } from "@lucide/svelte";
	import { onMount } from "svelte";

	type LogAction = "called" | "completed" | "no-show";
	const colors = {
		called: "var(--chart-1)",
		completed: "var(--chart-2)",
		"no-show": "var(--destructive)",
	}
	const text = {
		called: "Aufgerufen",
		completed: "Erledigt",
		"no-show": "Nicht erschienen",
	}
	const icons = {
		called: TicketSlashIcon,
		completed: TicketCheckIcon,
		"no-show": TicketXIcon,
	}

	interface LogEntry {
		ticket: string;
		time: string;
		action: LogAction;
		room: string | null;
	};

	let logs = $state<LogEntry[]>([]);

	onMount(() => {
		eventTarget.addEventListener("log", (e) => {
			const detail = (e as CustomEvent).detail;
			logs = detail.log;
		})

		eventTarget.dispatchEvent(new CustomEvent("send", { detail: { type: "get-log" } }));
	})
</script>

<h1 class="text-2xl font-bold">Log</h1>

<Table.Root>
	<Table.Header>
		<Table.Row>
			<Table.Head>Ticketnr.</Table.Head>
			<Table.Head>Zeit</Table.Head>
			<Table.Head>Aktion</Table.Head>
			<Table.Head>Raum</Table.Head>
		</Table.Row>
	</Table.Header>
	<Table.Body>
		{#each logs as log}
			<Table.Row>
				<Table.Cell class="font-medium">{log.ticket}</Table.Cell>
				<Table.Cell>{new Date(log.time).toLocaleString("de-de")}</Table.Cell>
				<Table.Cell style="display: flex; align-items: center; gap: 0.25rem; color: {colors[log.action]};">
					{@const Icon = icons[log.action]}
					<Icon />
					{text[log.action]}
				</Table.Cell>
				<Table.Cell>{log.room}</Table.Cell>
			</Table.Row>
		{/each}
	</Table.Body>
</Table.Root>