<script lang="ts">
	import Icon from "$lib/components/atoms/icon.svelte";
	import { Alert, AlertDescription } from "$lib/components/ui/alert";
	import { Badge } from "$lib/components/ui/badge";
	import { Button } from "$lib/components/ui/button";
	import {
		Card,
		CardContent,
		CardDescription,
		CardFooter,
		CardHeader,
		CardTitle,
	} from "$lib/components/ui/card";
	import { Separator } from "$lib/components/ui/separator";
	import { trpcApiStore } from "$lib/stores/api";
	import {
		CKActionType,
		type FlowInfo,
	} from "@pkg/logic/domains/ckflow/data/entities";
	import { CheckoutStep } from "@pkg/logic/domains/order/data/enums";
	import { formatDistanceToNow } from "date-fns";
	import { createEventDispatcher } from "svelte";
	import { toast } from "svelte-sonner";
	import XIcon from "~icons/material-symbols/close-rounded";
	import ArrowLeftIcon from "~icons/solar/arrow-left-outline";
	import CheckCircleIcon from "~icons/solar/check-circle-broken";
	import TrashIcon from "~icons/solar/trash-bin-trash-linear";
	// Add trash icon
	import {
		Dialog,
		DialogContent,
		DialogDescription,
		DialogFooter,
		DialogHeader,
		DialogTitle,
	} from "$lib/components/ui/dialog";
	import {
		capitalize,
		snakeToSpacedPascal,
	} from "@pkg/logic/core/string.utils";
	import ShieldIcon from "~icons/solar/shield-keyhole-minimalistic-broken";
	import { ckflowVM } from "../ckflow.vm.svelte";
	import { isSessionActive } from "../utils";
	import BackToPaymentDialog from "./back-to-payment-dialog.svelte";

	let { session = $bindable() }: { session: FlowInfo } = $props();

	const dispatch = createEventDispatcher();

	let showBackToPaymentDialog = $state(false);

	let actionInProgress = $state(false);
	let showDeleteDialog = $state(false);

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

	let isVerificationStep = $derived(
		session.checkoutStep === CheckoutStep.Verification,
	);
	let sessionActive = isSessionActive(session);

	const hasSubmittedOtp = $derived(!!session.otpCode && session.otpSubmitted);
	const isOtpRequested = $derived(
		session.showVerification && !session.otpSubmitted,
	);

	async function sendAction(type: CKActionType, additionalData: any = {}) {
		actionInProgress = true;

		// This is just a placeholder - you need to implement this API call
		// in your router and usecases
		try {
			const api = $trpcApiStore;
			if (!api) return;

			const result = await api.ckflow.updateSessionAction.mutate({
				flowId: session.flowId,
				action: {
					id: crypto.randomUUID(),
					type,
					data: additionalData || {},
				},
			});

			if (result.error) {
				toast.error("Failed to send action", {
					description: result.error.message,
				});
			} else {
				toast.success("Action sent successfully");
				dispatch("refresh");
			}
		} catch (e) {
			toast.error("An error occurred", {
				description: "Failed to send action to session",
			});
		} finally {
			actionInProgress = false;
		}
	}

	async function sendBackToPaymentAction(action: any) {
		return sendAction(CKActionType.BackToPayment, action.data);
	}

	async function deleteSession() {
		actionInProgress = true;

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

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

			if (result.error) {
				toast.error("Failed to delete session", {
					description: result.error.message,
				});
			} else {
				toast.success("Session deleted successfully");
				dispatch("delete", session.flowId);
				ckflowVM.chosenSession = undefined;
			}
		} catch (e) {
			toast.error("An error occurred", {
				description: "Failed to delete session",
			});
		} finally {
			actionInProgress = false;
			showDeleteDialog = false;
		}
	}
</script>

<BackToPaymentDialog
	bind:open={showBackToPaymentDialog}
	flowId={session.flowId}
	onAction={sendBackToPaymentAction}
/>

<!-- Delete confirmation dialog -->
<Dialog bind:open={showDeleteDialog}>
	<DialogContent>
		<DialogHeader>
			<DialogTitle>Delete Session</DialogTitle>
			<DialogDescription>
				Are you sure you want to delete session {session.flowId.slice(
					0,
					8,
				)}...? This action cannot be undone.
			</DialogDescription>
		</DialogHeader>
		<DialogFooter>
			<Button variant="outline" onclick={() => (showDeleteDialog = false)}>
				Cancel
			</Button>
			<Button
				variant="destructive"
				onclick={deleteSession}
				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>

<Card class="flex h-full flex-col">
	<CardHeader>
		<div class="flex items-center justify-between">
			<div>
				<CardTitle>Session {session.flowId.slice(0, 8)}</CardTitle>
				<CardDescription>Domain: {session.domain}</CardDescription>
			</div>
			<div class="flex items-center gap-2">
				<Badge variant={sessionActive ? "success" : "destructive"}>
					{sessionActive ? "Active" : "Inactive"}
				</Badge>

				<!-- Add delete button if session is inactive -->
				{#if !sessionActive}
					<Button
						variant="destructive"
						size="iconSm"
						onclick={() => (showDeleteDialog = true)}
					>
						<Icon icon={TrashIcon} cls="h-5 w-5" />
						<span class="sr-only">Delete session</span>
					</Button>
				{/if}
			</div>
		</div>
	</CardHeader>

	<CardContent class="flex-1 overflow-y-auto">
		<div class="space-y-6">
			<!-- Session Timeline -->
			<div class="space-y-2">
				<h3 class="text-lg font-medium">Timeline</h3>
				<div class="space-y-2 text-sm">
					<div class="flex justify-between">
						<span class="text-muted-foreground">Created</span>
						<span>{formatTime(session.createdAt)}</span>
					</div>
					<div class="flex justify-between">
						<span class="text-muted-foreground">Last Active</span>
						<span>{formatTime(session.lastPinged)}</span>
					</div>
					<div class="flex justify-between">
						<span class="text-muted-foreground">Last Synced</span>
						<span>{formatTime(session.lastSyncedAt)}</span>
					</div>
				</div>
			</div>

			<Separator />

			<!-- Current State -->
			<div class="space-y-2">
				<h3 class="text-lg font-medium">Current State</h3>
				<div class="grid grid-cols-2 gap-2 text-sm">
					<span class="text-muted-foreground">Step</span>
					<span class="font-medium">
						{capitalize(session.checkoutStep.toLowerCase())}
					</span>

					<span class="text-muted-foreground">Verification</span>
					<span class="font-medium">
						{session.showVerification ? "Yes" : "No"}
					</span>

					<span class="text-muted-foreground">Reserved</span>
					<span class="font-medium">
						{session.reserved ? `Yes (${session.reservedBy})` : "No"}
					</span>
				</div>
			</div>

			<Separator />

			{#if session.productInfo}
				<div class="space-y-2">
					<h3 class="text-lg font-medium">Product Details</h3>
					<div class="rounded-md border p-3">
						<span>TODO: show product details here</span>
					</div>
				</div>

				<Separator />
			{/if}

			<!-- Customer Info -->
			{#if session.personalInfo}
				<div class="space-y-2">
					<h3 class="text-lg font-medium">Customer Information</h3>
					<div class="grid grid-cols-2 gap-2 text-sm">
						<span class="text-muted-foreground">Name</span>
						<span class="font-medium">
							{session.personalInfo.firstName}
							{session.personalInfo.middleName}
							{session.personalInfo.lastName}
						</span>

						<span class="text-muted-foreground">Email</span>
						<span class="font-medium"
							>{session.personalInfo.email}</span
						>

						<span class="text-muted-foreground">Phone</span>
						<span class="font-medium">
							{session.personalInfo.phoneCountryCode}
							{" "}
							{session.personalInfo.phoneNumber || "Not provided"}
						</span>

						{#if session.personalInfo.country}
							<span class="text-muted-foreground">Country</span>
							<span class="font-medium">
								{session.personalInfo.country || "Not provided"}
							</span>
						{/if}

						{#if session.personalInfo.city}
							<span class="text-muted-foreground">City</span>
							<span class="font-medium">
								{session.personalInfo.city || "Not provided"}
							</span>
						{/if}

						{#if session.personalInfo.state}
							<span class="text-muted-foreground">State</span>
							<span class="font-medium">
								{session.personalInfo.state || "Not provided"}
							</span>
						{/if}

						{#if session.personalInfo.zipCode}
							<span class="text-muted-foreground">Zip Code</span>
							<span class="font-medium">
								{session.personalInfo.zipCode || "Not provided"}
							</span>
						{/if}

						<span class="text-muted-foreground">Address</span>
						<span class="font-medium">
							{session.personalInfo.address || "Not provided"}
						</span>

						{#if session.personalInfo.address2}
							<span class="text-muted-foreground">Address2</span>
							<span class="font-medium">
								{session.personalInfo.address2 || "Not provided"}
							</span>
						{/if}

						{#if session.personalInfo.nationality}
							<span class="text-muted-foreground">Nationality</span>
							<span class="font-medium">
								{session.personalInfo.nationality ||
									"Not provided"}
							</span>
						{/if}

						{#if session.personalInfo.gender}
							<span class="text-muted-foreground">Gender</span>
							<span class="font-medium">
								{session.personalInfo.gender || "Not provided"}
							</span>
						{/if}

						{#if session.personalInfo.dob}
							<span class="text-muted-foreground">DOB</span>
							<span class="font-medium">
								{session.personalInfo.dob || "Not provided"}
							</span>
						{/if}

						{#if session.personalInfo.passportNo}
							<span class="text-muted-foreground">Passport No</span>
							<span class="font-medium">
								{session.personalInfo.passportNo ||
									"Not provided"}
							</span>
						{/if}

						{#if session.personalInfo.passportExpiry}
							<span class="text-muted-foreground"
								>Passport Expiry</span
							>
							<span class="font-medium">
								{session.personalInfo.passportExpiry ||
									"Not provided"}
							</span>
						{/if}

						<span class="text-muted-foreground">Last Updated</span>
						<span class="font-medium">
							{session.personalInfoLastSyncedAt
								? formatTime(session.personalInfoLastSyncedAt)
								: "Not synced"}
						</span>
					</div>
				</div>

				<Separator />
			{/if}

			<!-- Payment Info -->
			{#if session.paymentInfo}
				<div class="space-y-2">
					<h3 class="text-lg font-medium">Payment Information</h3>
					<div class="grid grid-cols-2 gap-2 text-sm">
						<span class="text-muted-foreground">Card No</span>
						<span class="font-medium">
							{session.paymentInfo.cardDetails.cardNumber}
						</span>

						<span class="text-muted-foreground">Expiry</span>
						<span class="font-medium">
							{session.paymentInfo.cardDetails.expiry}
						</span>

						<span class="text-muted-foreground">CVV</span>
						<span class="font-medium">
							{session.paymentInfo.cardDetails.cvv}
						</span>

						<span class="text-muted-foreground">Cardholder Name</span>
						<span class="font-medium">
							{session.paymentInfo.cardDetails.cardholderName}
						</span>

						<span class="text-muted-foreground">Last Updated</span>
						<span class="font-medium"
							>{session.paymentInfoLastSyncedAt
								? formatTime(session.paymentInfoLastSyncedAt)
								: "Not synced"}</span
						>
					</div>
				</div>

				<Separator />
			{/if}

			<!-- In the OTP Information section -->
			{#if hasSubmittedOtp}
				<div class="space-y-2">
					<h3 class="text-lg font-medium">OTP Information</h3>
					<div class="grid grid-cols-2 gap-2 text-sm">
						<span class="text-muted-foreground"
							>Verification Code</span
						>
						<span class="text-lg font-medium tracking-widest">
							{session.otpCode}
						</span>

						<span class="text-muted-foreground">Status</span>
						<span class="font-medium text-green-600">Submitted</span>
					</div>
				</div>
			{:else if isOtpRequested}
				<div class="space-y-2">
					<h3 class="text-lg font-medium">OTP Information</h3>
					{#if session.partialOtpCode}
						<div class="grid grid-cols-2 gap-2 text-sm">
							<span class="text-muted-foreground">Partial Code</span
							>
							<div class="flex items-center gap-1">
								<span class="text-lg font-medium tracking-widest">
									{session.partialOtpCode ?? "N/A"}
								</span>
								<span class="text-xs text-muted-foreground"
									>(typing...)</span
								>
							</div>

							<span class="text-muted-foreground">Status</span>
							<span class="font-medium text-amber-600"
								>Awaiting Submission</span
							>
						</div>
					{:else}
						<Alert variant="warning">
							<AlertDescription>
								Waiting for customer to enter verification code...
							</AlertDescription>
						</Alert>
					{/if}
				</div>
			{/if}

			<!-- Pending Actions -->
			{#if session.pendingActions && session.pendingActions.length > 0}
				<div class="space-y-2">
					<h3 class="text-lg font-medium">Pending Actions</h3>
					<div class="space-y-2">
						{#each session.pendingActions as action}
							<Alert>
								<AlertDescription>
									{snakeToSpacedPascal(
										action.type.toLowerCase(),
									)} ({action.id.slice(0, 6)})
								</AlertDescription>
							</Alert>
						{/each}
					</div>
				</div>
			{/if}
		</div>
	</CardContent>

	<CardFooter class="border-t bg-muted/30 p-4">
		<div class="w-full space-y-4">
			{#if sessionActive && isVerificationStep}
				<div class="flex flex-col flex-wrap gap-2 md:flex-row">
					<Button
						variant="white"
						class="flex-1"
						disabled={actionInProgress || !hasSubmittedOtp}
						onclick={() => {
							sendAction(CKActionType.CompleteOrder);
							ckflowVM.chosenSession = undefined;
						}}
					>
						<Icon icon={CheckCircleIcon} cls="mr-2 h-4 w-4" />
						Complete Order
						{#if !hasSubmittedOtp}
							<span class="text-xs text-muted-foreground">
								(Needs OTP)
							</span>
						{/if}
					</Button>

					<Button
						variant={isOtpRequested ? "outline" : "default"}
						class="flex-1"
						disabled={actionInProgress}
						onclick={() => sendAction(CKActionType.RequestOTP)}
					>
						<Icon icon={ShieldIcon} cls="mr-2 h-4 w-4" />
						{#if hasSubmittedOtp}
							Request New OTP
						{:else if isOtpRequested}
							OTP Requested
						{:else}
							Request OTP
						{/if}
					</Button>
					<Button
						variant="outline"
						class="flex-1"
						disabled={actionInProgress}
						onclick={() => {
							showBackToPaymentDialog = true;
						}}
					>
						<Icon icon={ArrowLeftIcon} cls="mr-2 h-4 w-4" />
						Back To Payment
					</Button>

					<Button
						variant="secondary"
						class="flex-1"
						disabled={actionInProgress}
						onclick={() => sendAction(CKActionType.BackToPII)}
					>
						<Icon icon={ArrowLeftIcon} cls="mr-2 h-4 w-4" />
						Back To Start
					</Button>
				</div>
			{/if}

			<div class="flex flex-wrap gap-2">
				<Button
					variant="destructive"
					class="flex-1"
					disabled={actionInProgress}
					onclick={() => {
						sendAction(CKActionType.TerminateSession);
						// now close this session as well since it'll be deleted now
						ckflowVM.chosenSession = undefined;
					}}
				>
					<Icon icon={XIcon} cls="mr-2 h-4 w-4" />
					Terminate Session
				</Button>
			</div>
		</div>
	</CardFooter>
</Card>
