import React from "react";
import "./Add_to_card_btn.css";
import {
  faBasketShopping,
  faCartShopping,
  faChevronRight,
  faEye,
} 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";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

function Add_to_card_btn({
  id,
  product,
  quantity,
  isProductCard = false,
  setQuantity,
  cartItem,
  stock,
  inStock,
  onAdded,
}) {
  const navigate = useRouter(); // Step 2
  const isSignIn = useSelector((state) => state.auth.is_signin);
  const dispatch = useDispatch();

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

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

  const addToCart = async () => {
    const alreadyInCart = cartItem?.quantity || 0;

    if (alreadyInCart + quantity > stock) {
      setError?.(`Only ${stock} quantity in stock`);
      return;
    }

    const total = alreadyInCart + quantity;

    if (total > stock) {
      setError(`Only ${stock} quantity in stock`);
      return;
    }

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

      if (res.meta?.requestStatus === "fulfilled") {
        // handleClick();
        await dispatch(getAllCart(isSignin));
        onAdded?.();
        if (!isProductCard) {
          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);
    }
  };

  const data = {
    product_id: product.id,
    variant_id: selectedVariant?.id,
    quantity: quantity,
  };

  // const ress = await dispatch(postCart({ data, isSignIn }));
  return (
    <>
      <section className="Add_to_card_btn">
        {cartItem ? (
          <Green_Btn_With_Icon
            btnText={
              <>
                <span className="add_to_text">
                  {/* <FontAwesomeIcon icon={faChevronRight} /> */}
                  View
                </span>
              </>
            }
            viewIcon={faEye}
            onClick={() => handleClick()}
          />
        ) : (
          <Green_Btn_With_Icon
            btnText={
              <>
                <span className="add_to_text">Add to</span>
              </>
            }
            leftIcon={faCartShopping}
            onClick={
              isProductCard
                ? addToCart
                : () => navigate.push(`/product-details/${encodeId(id)}`)
            }
          />
        )}
      </section>
    </>
  );
}

export default Add_to_card_btn;
