<script lang="ts">
	import Icon from "$lib/components/atoms/icon.svelte";
	import { Badge } from "$lib/components/ui/badge";
	import { Button } from "$lib/components/ui/button";
	import * as ContextMenu from "$lib/components/ui/context-menu/index";
	import {
		Dialog,
		DialogContent,
		DialogDescription,
		DialogFooter,
		DialogHeader,
		DialogTitle,
	} from "$lib/components/ui/dialog";
	import { ScrollArea } from "$lib/components/ui/scroll-area";
	import { CheckoutStep } from "$lib/domains/order/data/entities";
	import { trpcApiStore } from "$lib/stores/api";
	import type { FlowInfo } from "@pkg/logic/domains/ckflow/data/entities";
	import { formatDistanceToNow } from "date-fns";
	import { toast } from "svelte-sonner";
	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 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(),
	}: {
		sessions: FlowInfo[];
		selectedSession: FlowInfo | undefined;
	} = $props();

	// State for delete dialog
	let showDeleteDialog = $state(false);
	let sessionToDelete: FlowInfo | undefined = $state(undefined);
	let actionInProgress = $state(false);

	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 handleDelete(session: FlowInfo) {
		sessionToDelete = session;
		showDeleteDialog = true;
	}

	async function confirmDelete() {
		if (!sessionToDelete) return;

		actionInProgress = true;

		try {
			const api = $trpcApiStore;
			if (!api) return;

			const result = await api.ckflow.deleteSession.mutate({
				flowId: sessionToDelete.flowId,
			});

			if (result.error) {
				toast.error("Failed to delete session", {
					description: result.error.message,
				});
			} else {
				toast.success("Session deleted successfully");
				// If the deleted session was selected, deselect it
				if (selectedSession?.flowId === sessionToDelete.flowId) {
					selectedSession = undefined;
				}
				// Remove the session from the list (this will be temporary until next refresh)
				sessions = sessions.filter(
					(s) => s.flowId !== sessionToDelete?.flowId,
				);
			}
		} catch (e) {
			toast.error("An error occurred", {
				description: "Failed to delete session",
			});
		} finally {
			actionInProgress = false;
			showDeleteDialog = false;
			sessionToDelete = undefined;
		}
	}
</script>

<!-- Delete Confirmation Dialog -->
<Dialog bind:open={showDeleteDialog}>
	<DialogContent>
		<DialogHeader>
			<DialogTitle>Delete Session</DialogTitle>
			<DialogDescription>
				Are you sure you want to delete session {sessionToDelete?.flowId.slice(
					0,
					8,
				)}...? This action cannot be undone.
			</DialogDescription>
		</DialogHeader>
		<DialogFooter>
			<Button variant="outline" onclick={() => (showDeleteDialog = false)}>
				Cancel
			</Button>
			<Button
				variant="destructive"
				onclick={confirmDelete}
				disabled={actionInProgress}
			>
				{#if actionInProgress}
					<span class="mr-2">Deleting...</span>
				{:else}
					<Icon icon={TrashIcon} cls="mr-2 h-4 w-4" />
					Delete
				{/if}
			</Button>
		</DialogFooter>
	</DialogContent>
</Dialog>

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

	<ScrollArea class="flex-1">
		{#if sessions.length === 0}
			<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>Waiting for any new sessions...</p>
			</div>
		{:else}
			<div class="space-y-2">
				{#each sessions as session, idx}
					{@const fn = session.personalInfo?.firstName ?? ""}
					{@const ln = session.personalInfo?.lastName ?? ""}
					<ContextMenu.Root>
						<ContextMenu.Trigger>
							<button
								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}
								onclick={() => (selectedSession = session)}
							>
								<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>
										<div
											class="absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-background"
											class:bg-green-500={isSessionActive(
												session,
											)}
											class:bg-red-500={!isSessionActive(
												session,
											)}
										></div>
									</div>

									<div class="flex flex-col">
										<span class="font-medium">
											{fn.length > 0
												? ln.length
													? `${fn} ${ln}`.slice(0, 9)
													: fn
												: session.flowId.slice(0, 6)}...
										</span>
										<span
											class="text-xs font-medium text-gray-600"
										>
											#{idx + 1}
										</span>
									</div>
								</div>

								<div class="flex flex-col items-end text-end">
									<span class="mb-1 text-end text-xs">
										{session.checkoutStep}
									</span>

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