<script lang="ts">
	import Container from "$lib/components/atoms/container.svelte";
	import Title from "$lib/components/atoms/title.svelte";
	import { pageTitle } from "$lib/hooks/page-title.svelte";
	import type { PageData } from "./$types";
	import { users } from "$lib/domains/user/data/store";
	import { userInfo } from "$lib/stores/session.info";
	import { ckflowVM } from "$lib/domains/ckflow/ckflow.vm.svelte";
	import { onMount, onDestroy } from "svelte";
	import ActiveSessionsList from "$lib/domains/ckflow/view/active-sessions-list.svelte";
	import SessionDetail from "$lib/domains/ckflow/view/session-detail.svelte";
	import {
		Alert,
		AlertDescription,
		AlertTitle,
	} from "$lib/components/ui/alert";
	import InfoIcon from "~icons/solar/shield-warning-linear";
	import Icon from "$lib/components/atoms/icon.svelte";

	pageTitle.set("Active Sessions");

	interface Props {
		data: PageData;
	}

	let { data }: Props = $props();

	userInfo.set(data.user);
	users.set(data.users ?? []);

	onMount(() => {
		ckflowVM.setupPoller();
	});

	onDestroy(() => {
		ckflowVM.clearPoller();
	});

	function handleRefresh() {
		ckflowVM.refreshSessionsList();
	}

	function handleDelete(event: CustomEvent<string>) {
		handleRefresh();
		if (ckflowVM.chosenSession) {
			ckflowVM.chosenSession = undefined;
		}
	}
</script>

<main class="grid w-full place-items-center pb-12 md:p-8">
	<div class="mb-4 flex w-full max-w-[90vw] items-center justify-between">
		<Title>Active Checkout Sessions</Title>
	</div>

	<div class="grid h-full w-full grid-cols-1 gap-4 lg:grid-cols-4">
		<Container
			containerClass="flex flex-col w-full h-full min-h-[44rem] lg:min-h-[80vh] overflow-hidden"
			wrapperClass="max-w-[90vw] lg:col-span-1"
		>
			<ActiveSessionsList
				sessions={ckflowVM.activeSessions}
				bind:selectedSession={ckflowVM.chosenSession}
			/>
		</Container>

		<Container
			containerClass="flex flex-col w-full h-full min-h-[44rem] lg:min-h-[80vh] overflow-hidden"
			wrapperClass="max-w-[90vw] lg:col-span-3"
		>
			{#if ckflowVM.chosenSession}
				<SessionDetail
					bind:session={ckflowVM.chosenSession}
					on:refresh={handleRefresh}
					on:delete={handleDelete}
				/>
			{:else}
				<div class="flex h-full items-center justify-center">
					<Alert>
						<Icon icon={InfoIcon} cls="h-4 w-4" />
						<AlertTitle>No session selected</AlertTitle>
						<AlertDescription>
							Select a session from the list to view details and
							manage the checkout flow.
						</AlertDescription>
					</Alert>
				</div>
			{/if}
		</Container>
	</div>
</main>
