"use client"; import { MinusIcon, PlusIcon } from "@heroicons/react/24/outline"; import clsx from "clsx"; import { useSearchParams } from "next/navigation"; import { useForm, useWatch } from "react-hook-form"; import { ConfigurableProductIndexData } from "@/types/types"; import { useAddProduct } from "@utils/hooks/useAddToCart"; import LoadingDots from "@components/common/icons/LoadingDots"; import { getVariantInfo } from "@utils/hooks/useVariantInfo"; import { safeParse } from "@utils/helper"; import { ProductSwatchReview } from "@/types/category/type"; interface AddToCartFormData { quantity: number; isBuyNow: boolean; } function SubmitButton({ selectedVariantId, pending, type, isSaleable, }: { selectedVariantId: boolean; pending: boolean; type: string; isSaleable: string; }) { const buttonClasses = "relative flex w-full max-w-[16rem] cursor-pointer h-fit items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white"; const disabledClasses = "cursor-wait opacity-60"; if (!isSaleable || isSaleable === "") { return ( ); } if (!selectedVariantId && type === "configurable") { return ( ); } return ( ); } export function AddToCart({ productSwatchReview, index, productId, userInteracted, }: { productSwatchReview: ProductSwatchReview; productId: string; index: ConfigurableProductIndexData[]; userInteracted: boolean; }) { const isSaleable = productSwatchReview?.isSaleable || ""; const { onAddToCart, isCartLoading } = useAddProduct(); const { handleSubmit, setValue, control, register } = useForm({ defaultValues: { quantity: 1, isBuyNow: false, }, }); const quantity = useWatch({ control, name: "quantity", }); const increment = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); setValue("quantity", Number(quantity) + 1); }; const decrement = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); setValue("quantity", Math.max(1, Number(quantity) - 1)); }; const searchParams = useSearchParams(); const type = productSwatchReview?.type; const superAttributes = productSwatchReview?.superAttributeOptions ? safeParse(productSwatchReview.superAttributeOptions) : productSwatchReview?.superAttributes?.edges?.map( (e) => e.node, ) || []; const isConfigurable = superAttributes.length > 0; const { productid: selectedVariantId, Instock: checkStock } = getVariantInfo( isConfigurable, searchParams.toString(), superAttributes, JSON.stringify(index), ); const buttonStatus = !!selectedVariantId; const actionWithVariant = async (data: AddToCartFormData) => { const pid = type === "configurable" ? String(selectedVariantId) : (String(productId).split("/").pop() ?? ""); onAddToCart({ productId: pid, quantity: data.quantity, }); }; return ( <> {!checkStock && type === "configurable" && userInteracted && (

NO STOCK AVAILABLE

)}
{quantity}
); }