<script lang="ts">
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Checkbox } from '$lib/components/ui/checkbox';

	let {
		cardNumber = $bindable(''),
		cardExpiry = $bindable(''),
		cardCVC = $bindable(''),
		saveCard = $bindable(false),
		showSaveCard = false,
		disabled = false
	}: {
		cardNumber?: string;
		cardExpiry?: string;
		cardCVC?: string;
		saveCard?: boolean;
		showSaveCard?: boolean;
		disabled?: boolean;
	} = $props();

	function formatNumber(value: string): string {
		const digits = value.replace(/\D/g, '').substring(0, 16);
		const groups = digits.match(/.{1,4}/g);
		return groups ? groups.join(' ') : digits;
	}

	function formatExpiry(value: string): string {
		const digits = value.replace(/\D/g, '').substring(0, 4);
		if (digits.length >= 3) {
			return digits.substring(0, 2) + '/' + digits.substring(2);
		}
		return digits;
	}
</script>

<div class="rounded-lg border border-gray-100 bg-gray-50 p-4">
	<h4 class="mb-4 text-sm font-medium text-gray-700">Card Details</h4>
	<div class="space-y-4">
		<div class="space-y-2">
			<Label for="cardNumber">Card Number</Label>
			<Input
				id="cardNumber"
				type="text"
				inputmode="numeric"
				value={cardNumber}
				oninput={(e) => (cardNumber = formatNumber((e.target as HTMLInputElement).value))}
				placeholder="1234 5678 9012 3456"
				maxlength={19}
				{disabled}
			/>
		</div>
		<div class="grid grid-cols-2 gap-4">
			<div class="space-y-2">
				<Label for="cardExpiry">Expiry (MM/YY)</Label>
				<Input
					id="cardExpiry"
					type="text"
					inputmode="numeric"
					value={cardExpiry}
					oninput={(e) => (cardExpiry = formatExpiry((e.target as HTMLInputElement).value))}
					placeholder="MM/YY"
					maxlength={5}
					{disabled}
				/>
			</div>
			<div class="space-y-2">
				<Label for="cardCVC">CVC</Label>
				<Input
					id="cardCVC"
					type="text"
					inputmode="numeric"
					bind:value={cardCVC}
					placeholder="123"
					maxlength={4}
					{disabled}
				/>
			</div>
		</div>
		{#if showSaveCard}
			<div class="flex items-center gap-2">
				<Checkbox id="saveCard" bind:checked={saveCard} {disabled} />
				<Label for="saveCard" class="text-sm font-normal">Save card for next time</Label>
			</div>
		{/if}
	</div>
</div>
