import { ckFlowVM } from "$lib/domains/ckflow/view/ckflow.vm.svelte";
import { CheckoutStep, newOrderModel } from "$lib/domains/order/data/entities";
import {
	paymentInfoPayloadModel,
	PaymentMethod,
} from "$lib/domains/paymentinfo/data/entities";
import { trpcApiStore } from "$lib/stores/api";
import { toast } from "svelte-sonner";
import { get } from "svelte/store";
import { currencyStore } from "../currency/view/currency.vm.svelte";
import { customerInfoVM } from "../customerinfo/view/customerinfo.vm.svelte";
import { productStore } from "../product/store";
import { paymentInfoVM } from "./payment-info-section/payment.info.vm.svelte";
import { calculateFinalPrices } from "./utils";

class CheckoutViewModel {
	checkoutStep = $state(CheckoutStep.Initial);
	loading = $state(true);
	continutingToNextStep = $state(false);

	checkoutSubmitted = $state(false);

	reset() {
		this.checkoutStep = CheckoutStep.Initial;
	}

	async checkout() {
		if (this.checkoutSubmitted || this.loading) {
			return;
		}
		this.checkoutSubmitted = true;

		const api = get(trpcApiStore);
		if (!api) {
			this.checkoutSubmitted = false;
			return false;
		}
		const product = get(productStore);

		if (!product || !customerInfoVM.customerInfo) {
			this.checkoutSubmitted = false;
			return false;
		}

		const priceDetails = calculateFinalPrices(
			product,
			customerInfoVM.customerInfo,
		);

		const parsed = newOrderModel.safeParse({
			...priceDetails,
			productId: product.id,
			currency: get(currencyStore).code,
		});

		if (parsed.error) {
			console.error("Order model validation error:", parsed.error.errors);
			const err = parsed.error.errors[0];
			toast.error("Failed to perform checkout", {
				description: `${err.path.join(".")}: ${err.message}`,
			});
			return false;
		}

		const pInfoParsed = paymentInfoPayloadModel.safeParse({
			orderId: -1,
			method: PaymentMethod.Card,
			cardDetails: paymentInfoVM.cardDetails,
			productId: get(productStore)?.id,
		});
		if (pInfoParsed.error) {
			console.error(
				"Payment info validation error:",
				pInfoParsed.error.errors,
			);
			const err = pInfoParsed.error.errors[0];
			toast.error("Failed to validate payment information", {
				description: `${err.path.join(".")}: ${err.message}`,
			});
			return false;
		}

		try {
			console.log("Creating order");
			this.loading = true;
			const out = await api.order.createOrder.mutate({
				productId: get(productStore)?.id,
				orderModel: parsed.data,
				customerInfo: customerInfoVM.customerInfo!,
				paymentInfo: pInfoParsed.data,
				flowId: ckFlowVM.flowId,
			});

			if (out.error) {
				this.loading = false;
				toast.error(out.error.message, {
					description: out.error.userHint,
				});
				return false;
			}
			if (!out.data) {
				this.loading = false;
				toast.error("Failed to create order", {
					description: "Please try again",
				});
				return false;
			}

			toast.success("Order created successfully", {
				description: "Redirecting, please wait...",
			});
			setTimeout(() => {
				window.location.href = `/checkout/success?uid=${out.data}`;
			}, 500);
			return true;
		} catch (e) {
			this.checkoutSubmitted = false;
			toast.error("An error occurred during checkout", {
				description: "Please try again",
			});
			return false;
		}
	}
}

export const checkoutVM = new CheckoutViewModel();
