"use client";
import { FC, ReactNode } from "react";
import { useAppDispatch } from "@/store/hooks";
import { openAddToCartDialog } from '@/store/slices/addToCartDialogSlice';
import { GET_PRODUCT_BY_URL_KEY } from "@/graphql";
import { useLazyQuery } from '@apollo/client/react';
import { SingleProductResponse } from "@/components/catalog/type";
import { LoadingSpinner } from "@components/common/LoadingSpinner";
import ShoppingCartIcon from "@components/common/icons/ShoppingCartIcon";
import { useCustomToast } from "@utils/hooks/useToast";
interface OpenAddToCartModalButtonProps {
  productUrlKey: string;
  icon?: ReactNode;
}
export const OpenAddToCartModalButton: FC<OpenAddToCartModalButtonProps> = ({
  productUrlKey,
  icon,
}) => {
    const dispatch = useAppDispatch();
    // const [loading, setLoading] = useState(false);
    const { showToast } = useCustomToast();

    const [getContent, { loading }] = useLazyQuery<SingleProductResponse>(GET_PRODUCT_BY_URL_KEY,{
        fetchPolicy: 'network-only'
    });
    const openDialog = async () => {
        if( loading) return; 
        try {
            const result = await getContent({
                variables: { urlKey: productUrlKey }
            });

            console.log('product ----- ', result);// 返回的数据中有__typename,如何过滤 @todo

            const productData = result?.data?.product;
            if(result.error) {
                showToast(result.error.message, "danger");
            } else {
                if(productData) {
                    dispatch(openAddToCartDialog(productData));
                } else {
                    //提示产品数据为空
                    showToast('Product data is null', "danger");
                }
            }
            
        } catch (error) {
            console.log('error ----- ', error);
            let errorMessage = "Network Error";
            if (error instanceof Error) {
                errorMessage = error.message;
            } else if (typeof error === 'object' && error !== null && 'message' in error) {
                errorMessage = String((error as any).message);
            }
            
            showToast(errorMessage, "danger");
        }
       
    }
    return (

        <button onClick={openDialog} disabled={loading}>
            { loading ? <LoadingSpinner colorClassName={"text-ly-green"} /> : <ShoppingCartIcon icon={icon} />}
        </button>
        
    );
};
