<script lang="ts">
	import ButtonLoadableText from "$lib/components/atoms/button-loadable-text.svelte";
	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 { checkoutVM } from "$lib/domains/checkout/checkout.vm.svelte";
	import { ckFlowVM } from "$lib/domains/ckflow/view/ckflow.vm.svelte";
	import { CheckoutStep } from "$lib/domains/order/data/entities";
	import { onMount } from "svelte";
	import { toast } from "svelte-sonner";
	import RightArrowIcon from "~icons/solar/arrow-right-broken";
	import CustomerPiiForm from "../customerinfo/view/customer-pii-form.svelte";
	import { customerInfoVM } from "../customerinfo/view/customerinfo.vm.svelte";

	$effect(() => {
		const personalInfo = customerInfoVM.customerInfo;

		if (!ckFlowVM.flowId || !ckFlowVM.setupDone || !personalInfo) return;

		// to trigger the effect
		const {
			phoneNumber,
			email,
			firstName,
			lastName,
			address,
			address2,
			zipCode,
			city,
			state,
			country,
		} = personalInfo;
		if (
			firstName ||
			lastName ||
			email ||
			phoneNumber ||
			country ||
			city ||
			state ||
			zipCode ||
			address ||
			address2
		) {
			console.log("pi ping");
			ckFlowVM.debouncePersonalInfoSync(personalInfo);
		}
	});

	async function proceedToNextStep() {
		customerInfoVM.validateCustomerInfo();
		console.log(customerInfoVM.errors);
		if (!customerInfoVM.isValid()) {
			return toast.error("Some or all info is invalid", {
				description: "Please properly fill out all of the fields",
			});
		}
		checkoutVM.continutingToNextStep = true;
		const out2 = await ckFlowVM.executePrePaymentStep();
		if (!out2) {
			return;
		}
		setTimeout(() => {
			checkoutVM.continutingToNextStep = false;
			checkoutVM.checkoutStep = CheckoutStep.Payment;
		}, 2000);
	}

	onMount(() => {
		window.scrollTo(0, 0);
		setTimeout(() => {
			customerInfoVM.initializeCustomerInfo();
		}, 200);
	});
</script>

{#if customerInfoVM.customerInfo}
	<div class="flex w-full flex-col gap-6">
		<Title size="h4" weight="medium">Personal Info</Title>
		<CustomerPiiForm bind:info={customerInfoVM.customerInfo} />
	</div>
{/if}

<div class="mt-8 flex flex-col items-center justify-between gap-4 border-t border-gray-200 pt-6 md:flex-row">
	<div></div>

	<Button
		variant="default"
		onclick={proceedToNextStep}
		class="w-full md:w-max"
		disabled={checkoutVM.continutingToNextStep}
	>
		<ButtonLoadableText
			text="Continue"
			loadingText="Processing..."
			loading={checkoutVM.continutingToNextStep}
		/>
		<Icon icon={RightArrowIcon} cls="w-auto h-6" />
	</Button>
</div>
