"use client";

import {use, useEffect} from "react";
import Link from "next/link";
import Image from "next/image";
import {FetchGraphqlResult} from "@/types/graphqlFetch/type";
import { OrderDetailsData,ProductItemAdditional } from "@/types/customer/type";
import { useConfig } from "@utils/hooks/useConfig";
import {getAddressFromOrderDetailAddressList} from "@/utils/orderDetailTools";
import Faqs from "./Faqs";



function getProductAdditionalInfo(productItem: ProductItemAdditional) { 
    const attributeKeys = Object.keys(productItem.attributes);
    let res = '';
    attributeKeys.forEach(key => {
      const attribute = productItem.attributes[key];
      if (attribute) {
        // option_label value_label

        if(res) {
            res = res + ', ' + attribute.option_label + ': ' + attribute.value_label;
        } else {
            res = attribute.option_label + ': ' + attribute.value_label;
        }
      }
    });
    return res;
}


export default function OrderDetailWrapper({
    orderDetailPromise,
    isGuest
}: {
    orderDetailPromise: Promise<FetchGraphqlResult<OrderDetailsData>>;
    isGuest: boolean;
}) { 

    const {currencies} = useConfig();
    const promiseRes = use(orderDetailPromise);
    const orderDetailRes = promiseRes.data.customerOrder;
    const shippingAddress = getAddressFromOrderDetailAddressList(orderDetailRes.addresses,"order_shipping");
    let orderCreatedAt = 'Can\'t get order date';
    if(orderDetailRes?.createdAt) {
        const localDate = new Date(orderDetailRes.createdAt);
        orderCreatedAt = localDate.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
    }
    const productItems = orderDetailRes?.items?.edges.map(item => {
        return item.node;
    }) || [];
    const currency = currencies?.find(item => item.code === orderDetailRes?.orderCurrencyCode) || null;

    useEffect(() => {
        // 如果是游客且支付成功，删除cookie里的GUEST_CART_TOKEN GUEST_CART_ID
        /**Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options */

        if(isGuest) {
            fetch("/api/clearCartCookie",{
                method:"POST"
            });
        }
    }, [isGuest]);

    return (
        <>
            <div className="box-border px-4 w-full">
                <div className="w-12 h-12 mx-auto mt-9">
                    <svg className="block w-full h-full" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="48" height="48" viewBox="0 0 48 48" fill="none"><path d="M24 44C29.5228 44 34.5228 41.7614 38.1421 38.1421C41.7614 34.5228 44 29.5228 44 24C44 18.4772 41.7614 13.4772 38.1421 9.85786C34.5228 6.23858 29.5228 4 24 4C18.4772 4 13.4772 6.23858 9.85786 9.85786C6.23858 13.4772 4 18.4772 4 24C4 29.5228 6.23858 34.5228 9.85786 38.1421C13.4772 41.7614 18.4772 44 24 44Z" stroke="rgba(0, 0, 0, 1)" strokeWidth="3" strokeLinejoin="round"  ></path><path    stroke="rgba(0, 0, 0, 1)" strokeWidth="3"  strokeLinecap="square"  d="M16 24L22 30L34 18"></path></svg>
                </div>
                <p className="text-ly-16 text-center mt-6">Your Order Has Been Received</p>
                <p className="text-ly-16 mt-4 flex justify-center">
                    <span className="px-3.75 leading-ly-28 bg-[#f0fffa]">Order #{orderDetailRes?._id}</span>
                </p>
                <p className="text-ly-12 text-center mt-4 leading-ly-22">
                    Hello, {orderDetailRes?.customerFirstName} <br/>
                    Thank you so much for your order !<br/>
                    We’ll get started on your order very soon!<br/>
                    You’ll receive an order confirmation email with details of your order in an hour, please be sure to check your email and confirm your order, that is very important for us to process your order.
                </p>
                <Link href="/" className="mt-6 flex justify-center items-center h-12 border-1 rounded-3xl text-ly-14">
                    Continue Shopping
                </Link>
            </div>
            <div className="box-border px-4 w-full mt-6">
                <Faqs />
            </div>
            <div className="box-border px-4 w-full mt-6">
                <h4 className="text-ly-24 font-medium">Order Information</h4>
                <div className="mt-6 flex justify-between">
                    <div className="text-ly-12 flex-none">Ship to:</div>
                    <div className="w-40.5 text-ly-12 leading-ly-20 text-[#666666] flex-none">
                        {
                            shippingAddress.firstName 
                            + ' ' + shippingAddress.lastName 
                            + ' ' + shippingAddress.phone
                            + ' ' + shippingAddress.address
                            + ' ' + shippingAddress.city
                            + ' ' + shippingAddress.state 
                            + ' ' + shippingAddress.postcode
                            + ' ' + shippingAddress.country
                        }
                    </div>
                </div>
                <div className="mt-6 flex justify-between">
                    <div className="text-ly-12 flex-none">Order number:</div>
                    <div className="w-40.5 text-ly-12 leading-ly-20 text-[#666666] flex-none">
                        {orderDetailRes?._id}
                    </div>
                </div>
                <div className="mt-6 flex justify-between">
                    <div className="text-ly-12 flex-none">Status:</div>
                    <div className="w-40.5 text-ly-12 leading-ly-20 text-[#666666] flex-none capitalize">
                        {orderDetailRes?.status}
                    </div>
                </div>
                <div className="mt-6 flex justify-between">
                    <div className="text-ly-12 flex-none">Order date:</div>
                    <div className="w-40.5 text-ly-12 leading-ly-20 text-[#666666] flex-none">
                        {orderCreatedAt}
                    </div>
                </div>
                <div className="mt-6 flex justify-between">
                    <div className="text-ly-12 flex-none">Shipping method:</div>
                    <div className="w-40.5 text-ly-12 leading-ly-20 text-[#666666] flex-none">
                        {orderDetailRes?.shippingTitle}
                    </div>
                </div>
                <div className="mt-6 flex justify-between">
                    <div className="text-ly-12 flex-none">Payment method:</div>
                    <div className="w-40.5 text-ly-12 leading-ly-20 text-[#666666] flex-none">
                        {orderDetailRes?.payment?.methodTitle}
                    </div>
                </div>

            </div>

            <div className="box-border px-4 w-full mt-6">
                {productItems.map((product) => {
                    return (
                        <div key={product.id} className="w-full flex gap-2 pb-4 border-b-1 border-[#f0f0f0] last:border-0 last:pb-0">
                            <div className="relative w-33 h-44 flex-none">
                                <Image fill src="https://cdn.alipearlhair.com/media/catalog/product/2/_/2_104_20.jpg" alt="logo" />
                            </div>
                            <div className="flex-none w-50.75 flex flex-col justify-between">
                                <div>
                                    <p className="text-ly-12 leading-ly-20 line-clamp-2">
                                        {product.name}
                                    </p>
                                    {
                                        product.additional && 
                                        <p className="mt-2 text-ly-12 leading-ly-20 text-ly-placeholder">
                                            {getProductAdditionalInfo(JSON.parse(product.additional))}
                                        </p>
                                    }
                                    
                                </div>
                                <div className="flex justify-between">
                                    <p className="text-ly-14 leading-ly-20 font-bold">
                                        {currency && currency.symbol}{product.price}
                                    </p>
                                    <p className="text-ly-12 leading-ly-20">x {product.qtyOrdered}</p>
                                </div>
                            </div>
                        </div>
                    );
                })}
                
            </div>

            <div className="box-border px-4 w-full mt-6 pt-6 border-t-1 border-black">
                <div className="flex justify-between mt-3 first:mt-0">
                    <p className="text-ly-12 leading-ly-20">Subtotal</p>
                    <p className="text-ly-12 leading-ly-20">{currency && currency.symbol}{orderDetailRes?.subTotal}</p>
                </div>
                <div className="flex justify-between mt-3 first:mt-0">
                    <p className="text-ly-12 leading-ly-20">Shipping</p>
                    <p className="text-ly-12 leading-ly-20">{currency && currency.symbol}{orderDetailRes?.shippingAmount}</p>
                </div>
                <div className="flex justify-between mt-3 first:mt-0">
                    <p className="text-ly-12 leading-ly-20">Tax</p>
                    <p className="text-ly-12 leading-ly-20">{currency && currency.symbol}{orderDetailRes?.taxAmount}</p>
                </div>
                <div className="flex justify-between mt-3 first:mt-0">
                    <p className="text-ly-12 leading-ly-20">Discount</p>
                    <p className="text-ly-12 leading-ly-20">{currency && currency.symbol}{orderDetailRes?.discountAmount}</p>
                </div>
                {/* <div className="flex justify-between mt-3 first:mt-0">
                    <p className="text-ly-12 leading-ly-20">You Earn</p>
                    <p className="text-ly-12 leading-ly-20">600 Reward Points</p>
                </div> */}
                <div className="flex justify-between mt-3 first:mt-0">
                    <p className="text-ly-16 leading-ly-24">Total</p>
                    <p className="text-ly-16 leading-ly-24 font-bold">{currency && currency.symbol}{orderDetailRes?.grandTotal}</p>
                </div>
            </div>
        </>
    );
}