import React from "react";
import "./Add_to_card_btn.css";
import { faBasketShopping, } from "@fortawesome/free-solid-svg-icons";

import { encodeId } from "../../../../utils/common";
import { useDispatch, useSelector } from "react-redux";
import { getAllCart, postCart } from "../../../../features/cart/cartSlice";
import Green_Btn_With_Icon from "../green_btn_with_icon/Green_Btn_With_Icon";
import { useRouter } from "next/navigation";

function Add_to_card_btn({ id, product }) {
  const navigate = useRouter(); // Step 2
  const isSignIn = useSelector((state) => state.auth.is_signin);
  const dispatch = useDispatch();

  const selectedVariant = product?.Product_Variants?.[0];
  const handleClick = () => {
    navigate.push(`/product-cart?product_id=${product?.id}`);
  };

   const isSignin = useSelector((state) => state.auth.is_signin);

  const addToCart = async () => {
    try {
      
      const data = {
        product_id: product.id,
        variant_id: selectedVariant?.id,
        quantity: 1,
      };
      const res = await dispatch(postCart({ data: data, isSignIn: isSignIn }));

      if (res.meta?.requestStatus === "fulfilled") {
        handleClick();
        await dispatch(getAllCart(isSignin));
        window.scrollTo({ top: 0, behavior: "smooth" });
        if (res?.payload?.data?.success) {
        } else {
        }
      } else if (res.meta?.requestStatus === "rejected") {
        console.log("Error:", res.payload || "Not In Cart");
      }
    } catch (error) {
      console.log("Error:", error);
    }
  };
  return (
    <>
      <section className="Add_to_card_btn">
        {/* {Number(selectedVariant?.general_stock) < 1 ? (
          <Brown_btn
            btnText="Out of stock"
            // onClick={addToCart}
            // onClick={() => navigate(`/product-details/${encodeId(id)}`)} // Step 3
          />
        ) : ( */}
          <Green_Btn_With_Icon
            btnText="Add to cart"
            leftIcon={faBasketShopping}
            onClick={() => navigate.push(`/product-details/${encodeId(id)}`)} // Step 3
          />
        {/* )} */}

        {/* old code */}
        {/* <Green_btn
          btnText={
            <>
              <FontAwesomeIcon icon={faCartShopping} />
            </>
          }
          onClick={() => navigate(`/product-details/${encodeId(id)}`)} 
        /> */}
      </section>
    </>
  );
}

export default Add_to_card_btn;
