import {Suspense} from "react";
import { getServerSession } from "next-auth";
import { redirect, RedirectType } from 'next/navigation';
import { authOptions } from "@utils/auth";
import {serverGraphqlFetch} from "@utils/bagisto/index";
import ContinueToPayOrderInfo from "../_components/ContinueToPay/ContinueToPayOrderInfo";
import { GET_ORDER_DETAILS, GET_REPAYORDER_PAYMENT_METHODS } from "@/graphql";
// import { Country } from "@/types/checkout/type";
import { OrderDetailsData } from "@/types/customer/type";
import { RepayOrderPaymentMethodsData } from "@/types/checkout/type";
import {PaymentMethodContinueTpPay} from "../_components/ContinueToPay/PaymentMethodContinueTpPay";
import LoadingPaymentMethod from "../_components/LoadingPaymentMethod";

// 只能存在一个待支付订单
export const dynamic = "force-dynamic";
// searchParams orderid
// 游客不能进入该页面
// 24小时倒计时
// 地址信息
// 购买产品
// 金额明细
// 支付方式
// 支付按钮


// express: false
// gatewayOrderId: "76B005629R5441508"
// id: "2602"
// message: "Payment initiated successfully"
// newCartToken: null
// orderId:  "2602"
// status: "pending"
// success: true
export default async function ContinueToPay({searchParams}: {
  searchParams?: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
    
    const session = await getServerSession(authOptions);// 游客是null
    // 游客跳转首页
    if(session === null) {
        redirect('/', RedirectType.replace);
    }

    const query = await searchParams;
    const orderid = query?.orderid;
    const {data: orderDetailResponse} = await serverGraphqlFetch<OrderDetailsData,{id:string}>({
        query: GET_ORDER_DETAILS,
        variables: {
            id: orderid as string
        }
    }); 
    const orderDetailData = orderDetailResponse.customerOrder;
    if(!orderDetailData  || orderDetailData?.status !== "pending")  {
        redirect('/', RedirectType.replace);
    }

    // 获取支付方式列表
    const paymentMethodsResponse = serverGraphqlFetch<RepayOrderPaymentMethodsData,{orderId:number}>({
        query: GET_REPAYORDER_PAYMENT_METHODS,
        variables: {
            orderId:  Number(orderid)
        }
    });
      

    return (
        <div className="w-full pb-8">
        
            <ContinueToPayOrderInfo orderDetail={orderDetailData} />
           
            <div className="mt-6 box-border px-4">
                <h3 className="text-ly-24 font-medium">Payment Method</h3>

            </div>
            <Suspense fallback={<LoadingPaymentMethod/>}> 
                <PaymentMethodContinueTpPay 
                    orderId={orderDetailData._id}
                    orderDetail={orderDetailData}
                    paymentMethodsDataPromise={paymentMethodsResponse}
                    defaultPaymentMethod={orderDetailData.payment}
                />
            </Suspense>
            
        </div>
    );
  
}
