<script lang="ts">
	import Icon from "$lib/components/atoms/icon.svelte";
	import { Badge } from "$lib/components/ui/badge";
	import * as ContextMenu from "$lib/components/ui/context-menu/index";
	import { ScrollArea } from "$lib/components/ui/scroll-area";
	import { CheckoutStep } from "$lib/domains/order/data/entities";
	import type { FlowInfo } from "@pkg/logic/domains/ckflow/data/entities";
	import { formatDistanceToNow } from "date-fns";
	import LoaderIcon from "~icons/bx/loader-alt";
	import UserIcon from "~icons/material-symbols/account-circle-full";
	import CreditCardIcon from "~icons/solar/card-2-linear";
	import CheckCircleIcon from "~icons/solar/check-circle-linear";
	import QuestionMarkIcon from "~icons/solar/question-circle-linear";
	import RestoreIcon from "~icons/solar/restart-bold";
	import ShieldAlertIcon from "~icons/solar/shield-warning-linear";
	import StopCircleIcon from "~icons/solar/stop-circle-linear";
	import TrashIcon from "~icons/solar/trash-bin-trash-linear";
	import { isSessionActive } from "../utils";

	let {
		sessions,
		selectedSession = $bindable(),
		includeDeleted = false,
		isLoading = false,
		onSoftDelete,
		onRestore,
	}: {
		sessions: FlowInfo[];
		selectedSession: FlowInfo | undefined;
		includeDeleted?: boolean;
		isLoading?: boolean;
		onSoftDelete: (flowId: string) => void;
		onRestore: (flowId: string) => void;
	} = $props();

	function getStepIcon(session: FlowInfo) {
		if (
			session.showVerification &&
			session.checkoutStep === CheckoutStep.Verification
		) {
			return ShieldAlertIcon;
		}
		switch (session.checkoutStep) {
			case CheckoutStep.Initial:
				return UserIcon;
			case CheckoutStep.Payment:
				return CreditCardIcon;
			case CheckoutStep.Verification:
				return QuestionMarkIcon;
			case CheckoutStep.Confirmation:
				return CheckCircleIcon;
			case CheckoutStep.Complete:
				return CheckCircleIcon;
			default:
				return StopCircleIcon;
		}
	}

	function formatTime(isoString: string): string {
		try {
			return formatDistanceToNow(new Date(isoString), { addSuffix: true });
		} catch (e) {
			return "Invalid date";
		}
	}

	function handleSoftDelete(session: FlowInfo) {
		onSoftDelete(session.flowId);
	}

	function handleRestore(session: FlowInfo) {
		onRestore(session.flowId);
	}
</script>

<div class="flex h-full flex-col">
	<div class="mb-4 flex items-center justify-between">
		<h2 class="text-xl font-bold">Sessions</h2>
		<Badge variant="outline">{sessions.length}</Badge>
	</div>

	<ScrollArea class="flex-1">
		{#if isLoading}
			<div class="mt-4 p-4 text-center text-muted-foreground">
				<Icon icon={LoaderIcon} cls="mx-auto mb-2 h-8 w-8 animate-spin" />
				<p>Loading sessions...</p>
			</div>
		{:else if sessions.length === 0}
			<div class="mt-4 p-4 text-center text-muted-foreground">
				<p>No sessions found</p>
			</div>
		{:else}
			<div class="space-y-2">
				{#each sessions as session (session.flowId)}
					{@const fn = session.personalInfo?.firstName ?? ""}
					{@const ln = session.personalInfo?.lastName ?? ""}
					{@const fullName =
						fn.length > 0 ? (ln.length > 0 ? `${fn} ${ln}` : fn) : ""}
					<ContextMenu.Root>
						<ContextMenu.Trigger>
							<div
								class="flex w-full items-center justify-between rounded-md border p-3 text-left transition-colors hover:bg-accent hover:text-accent-foreground"
								class:bg-accent={selectedSession?.flowId ===
									session.flowId}
								class:text-accent-foreground={selectedSession?.flowId ===
									session.flowId}
								class:opacity-60={session.isDeleted}
								onclick={() => (selectedSession = session)}
								onkeydown={(e) => {
									if (e.key === "Enter" || e.key === " ") {
										selectedSession = session;
									}
								}}
								role="button"
								tabindex="0"
							>
								<div class="flex items-center gap-3">
									<div class="relative">
										<div
											class="grid h-10 w-10 place-items-center rounded-full bg-muted"
										>
											{#if getStepIcon(session)}
												<Icon
													icon={getStepIcon(session)}
													cls="h-5 w-5"
												/>
											{/if}
										</div>
										{#if !session.isDeleted}
											<div
												class="absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-background"
												class:bg-green-500={session.isActive &&
													isSessionActive(session)}
												class:bg-yellow-500={!session.isActive}
												class:bg-red-500={session.isActive &&
													!isSessionActive(session)}
											></div>
										{/if}
									</div>

									<div class="flex flex-col">
										<span class="font-medium">
											{fullName.length > 0
												? fullName
												: "Name not available"}
										</span>
										<span
											class="max-w-xs truncate text-xs text-muted-foreground"
										>
											{(session.personalInfo?.email ?? "")
												.length > 0
												? session.personalInfo?.email
												: "Email not available"}
										</span>
									</div>
								</div>

								<div class="flex flex-col items-end text-end">
									<div class="flex items-center gap-2">
										<span class="mb-1 text-end text-xs">
											{session.checkoutStep}
										</span>
										{#if session.isDeleted}
											<Badge
												variant="destructive"
												class="text-xs">Deleted</Badge
											>
										{:else if !session.isActive}
											<Badge
												variant="secondary"
												class="text-xs">Inactive</Badge
											>
										{/if}
									</div>

									<span class="text-xs text-muted-foreground">
										{formatTime(session.lastPinged)}
									</span>
								</div>
							</div>
						</ContextMenu.Trigger>
						<ContextMenu.Content>
							{#if session.isDeleted}
								<ContextMenu.Item
									class="flex items-center gap-2"
									onclick={() => handleRestore(session)}
								>
									<Icon icon={RestoreIcon} cls="h-4 w-4" />
									<span>Restore Session</span>
								</ContextMenu.Item>
							{:else}
								<ContextMenu.Item
									class="flex items-center gap-2"
									onclick={() => handleSoftDelete(session)}
								>
									<Icon icon={TrashIcon} cls="h-4 w-4" />
									<span>Delete Session</span>
								</ContextMenu.Item>
							{/if}
						</ContextMenu.Content>
					</ContextMenu.Root>
				{/each}
			</div>
		{/if}
	</ScrollArea>
</div>
