"use client";

import { usePlaceOrder } from "@/utils/hooks/usePlaceOrder";
import PaypalButton from "./PaymentButton/PaypalButton";
import { overlayLoading } from "@/components/theme/ui/kernel/loading/api";
import { confirmDialog } from "@/components/theme/ui/kernel/confirm/api";
import { useAppDispatch } from "@/store/hooks";
import { clearCart } from "@/store/slices/cart-slice";
export default function CheckoutPlaceOrder({
    paymentMethod,
    clickPlaceOrder, // 校验运输方式，地址 
}: {
    paymentMethod: string;
    clickPlaceOrder: () => Promise<boolean>;
}) {
    const dispatch = useAppDispatch(); 

    const { createOrder } = usePlaceOrder(); 
    
    const handleCreateOrder = async () => {
        const res = await createOrder();
        console.log("createOrder res ---- ", res);
        if(!res.error && res.data) {
            //创建订单成功后清空redux 购物车
            dispatch(clearCart());
            return {
                error: res.error,
                msg: '',
                orderId: res.data.gatewayOrderId,
                webOrderId: res.data.orderId
            };
        } else {
            return {
                error: res.error,
                msg: res.msg,
                orderId: res.data?.gatewayOrderId ?? '',
                webOrderId: res.data?.orderId ?? ''
            };
        }
    };

    const airwallexPlaceOrder = async () => {
        overlayLoading.start();
        const vaild = await clickPlaceOrder();
        if(vaild) {
            const res = await createOrder({
                paymentSuccessUrl: window.location.origin + '/paymentresult/result'
            });
            console.log("createOrder res ---- ", res);
            if(!res.error && res.data) {
                // 创建订单成功了，跳转支付页面
                //创建订单成功后清空redux 购物车
                dispatch(clearCart());
                window.location.href = res.data.gatewayOrderId;
            } else {
                //创建订单出错了
                overlayLoading.stop();
                confirmDialog({
                    title: "Warning",
                    content: res.msg + " Create order failed. Please try again.",
                    noCancel: true,
                }).then(() => {});
            }
        } else {
            overlayLoading.stop();
        }
    };

    return (
        <>
            <div className="relative w-full">
                {paymentMethod === 'paypal_smart_button' && 
                    <PaypalButton
                        createOrder={handleCreateOrder}
                        onPaymentClick={clickPlaceOrder}
                    />
                }
                {(paymentMethod === 'awxklarna' || paymentMethod === 'awxafterpay') &&
                    <button className="flex items-center justify-center w-full h-12 bg-ly-green text-white rounded-3xl text-ly-16 font-bold"
                        onClick={airwallexPlaceOrder}
                    >
                        Place Order
                    </button>
                }

            </div>
        </>
    );
}
