<script lang="ts">
	import { Button } from "$lib/components/ui/button";
	import {
		Dialog,
		DialogContent,
		DialogDescription,
		DialogFooter,
		DialogHeader,
		DialogTitle,
	} from "$lib/components/ui/dialog";
	import { Label } from "$lib/components/ui/label";
	import { RadioGroup, RadioGroupItem } from "$lib/components/ui/radio-group";
	import { Textarea } from "$lib/components/ui/textarea";
	import {
		CKActionType,
		PaymentErrorType,
	} from "@pkg/logic/domains/ckflow/data/entities";

	let {
		open = $bindable<boolean>(false),
		flowId = $bindable<string>(""),
		onAction = $bindable<(action: any) => Promise<void>>(() =>
			Promise.resolve(),
		),
	} = $props();

	const errorOptions = [
		{
			type: PaymentErrorType.DO_NOT_HONOR,
			message: "Card not approved by your bank.",
			description:
				"This can happen for various reasons. Please try again, use another card, or contact your bank to resolve it quickly.",
		},
		{
			type: PaymentErrorType.REFER_TO_ISSUER,
			message: "Transaction declined by your bank.",
			description:
				"Your bank needs to verify something. A quick call should clear it up, or you can use a different payment method.",
		},
		{
			type: PaymentErrorType.TRANSACTION_DENIED,
			message: "Payment couldn't be completed.",
			description:
				"Your bank declined the transaction. Please contact them for help or try a different card to continue.",
		},
		{
			type: PaymentErrorType.CAPTURE_CARD_ERROR,
			message: "There's an issue with this card.",
			description:
				"Your bank has flagged this card. Please reach out to them for assistance or use a different one to complete your payment.",
		},
		{
			type: PaymentErrorType.CUSTOM_ERROR,
			message: "",
			description: "",
		},
	];

	let selectedErrorType = $state<PaymentErrorType>(
		PaymentErrorType.DO_NOT_HONOR,
	);
	let customMessage = $state("");
	let customDescription = $state("");
	let isSubmitting = $state(false);

	let showCustomFields = $derived(
		selectedErrorType === PaymentErrorType.CUSTOM_ERROR,
	);

	async function handleSubmit() {
		if (isSubmitting) return;
		isSubmitting = true;

		try {
			// Find the selected error or create custom one
			let errorPayload = errorOptions.find(
				(e) => e.type === selectedErrorType,
			);

			if (selectedErrorType === PaymentErrorType.CUSTOM_ERROR) {
				errorPayload = {
					type: PaymentErrorType.CUSTOM_ERROR,
					message: customMessage || "Payment couldn't be processed.",
					description:
						customDescription ||
						"Please try again or use a different payment method.",
				};
			}

			await onAction({
				id: crypto.randomUUID(),
				type: CKActionType.BackToPayment,
				data: {
					errorType: errorPayload?.type,
					message: errorPayload?.message,
					description: errorPayload?.description,
				},
			});

			open = false;
		} finally {
			isSubmitting = false;
		}
	}

	function handleCancel() {
		open = false;
	}
</script>

<Dialog bind:open>
	<DialogContent class="sm:max-w-md">
		<DialogHeader>
			<DialogTitle>Back to Payment with Error</DialogTitle>
			<DialogDescription>
				Select an error message to display to the customer when sending
				them back to the payment step.
			</DialogDescription>
		</DialogHeader>

		<div class="mt-4 space-y-6">
			<RadioGroup bind:value={selectedErrorType}>
				{#each errorOptions as option}
					{#if option.type !== PaymentErrorType.CUSTOM_ERROR}
						<div
							class="flex items-start space-x-2 rounded-md border p-3 hover:bg-muted/50"
						>
							<RadioGroupItem
								value={option.type}
								id={option.type}
							/>
							<div class="space-y-1.5">
								<Label for={option.type} class="font-medium"
									>{option.message}</Label
								>
								<p class="text-sm text-muted-foreground">
									{option.description}
								</p>
							</div>
						</div>
					{:else}
						<div
							class="flex items-start space-x-2 rounded-md border p-3 hover:bg-muted/50"
						>
							<RadioGroupItem
								value={option.type}
								id={option.type}
							/>
							<div class="w-full space-y-1.5">
								<Label for={option.type} class="font-medium"
									>Custom Error Message</Label
								>
								<p class="mb-2 text-sm text-muted-foreground">
									Define your own error message
								</p>

								{#if showCustomFields}
									<div class="mt-2 space-y-3">
										<div class="space-y-1">
											<Label for="custom-message"
												>Main Message</Label
											>
											<Textarea
												id="custom-message"
												placeholder="Enter main error message"
												bind:value={customMessage}
												rows={1}
											/>
										</div>
										<div class="space-y-1">
											<Label for="custom-description"
												>Description</Label
											>
											<Textarea
												id="custom-description"
												placeholder="Enter error description"
												bind:value={customDescription}
												rows={2}
											/>
										</div>
									</div>
								{/if}
							</div>
						</div>
					{/if}
				{/each}
			</RadioGroup>
		</div>

		<DialogFooter class="mt-4">
			<Button variant="outline" onclick={handleCancel}>Cancel</Button>
			<Button
				variant="default"
				onclick={handleSubmit}
				disabled={isSubmitting ||
					(showCustomFields && (!customMessage || !customDescription))}
			>
				{isSubmitting ? "Sending..." : "Send Error"}
			</Button>
		</DialogFooter>
	</DialogContent>
</Dialog>
