import React, { useEffect, useState } from "react";
import "./Product_Info_Card.css";
import Best_seller_heart from "../product_card/Best_seller_heart/Best_seller_heart";
import Add_to_card_btn from "../common_btn/Add_to_card_btn/Add_to_card_btn";

import { encodeId, RoleId, variant_type } from "../../../utils/common";
import { useSelector } from "react-redux";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Increment_decrement_btn_holder_add from "../common_btn/increment_decrement_btn_holder/Increment_decrement_btn_holder_add";
import { Modal } from "react-bootstrap";

const Product_Info_Card = ({
  id,
  imgSrc,
  vdoSrc,
  productName,
  priceText,
  mrp,
  product,
  showQty,
  kgText,
  variant,
}) => {
  const navigate = useRouter();

  const [quantity, setQuantity] = useState(1);

  const selectedVariant = product?.Product_Variants?.[0];
  const [showStockErrorPopup, setShowStockErrorPopup] = useState(false);
  const [stockError, setStockError] = useState("");
  const [showCartPopup, setShowCartPopup] = useState(false);
  const [inStock, setInStock] = useState(false);
  useEffect(() => {
    if (inStock && stockError) {
      setShowStockErrorPopup(true);

      const timer = setTimeout(() => {
        setShowStockErrorPopup(false);
        setStockError("");
      }, 2500);

      return () => clearTimeout(timer);
    }
  }, [stockError, inStock]);
  const cartItems = useSelector((state) => state.cart.allCarts.data || []);

  const cartItem = cartItems.find((item) => {
    if (Number(product.variant_type_id) === Number(variant_type.Single)) {
      return (
        Number(item.product_id) === Number(product.id) &&
        Number(item.variant_id) === Number(selectedVariant?.id)
      );
    }

    if (Number(product.variant_type_id) === Number(variant_type.Double)) {
      return (
        Number(item.product_id) === Number(product.id) &&
        Number(item.variant_id) === Number(selectedVariant?.id)
      );
    }

    return (
      Number(item.product_id) === Number(product.id) &&
      Number(item.t_variant_id) === Number(selectedVariant?.id)
    );
  });
  const displayQty = cartItem ? cartItem.quantity : quantity;
  const stock = Number(selectedVariant?.general_stock || 0);
  const isOutOfStock = Number(selectedVariant?.general_stock || 0) <= 0;

  const isSignin = useSelector((state) => state.auth.is_signin);
  const user = useSelector((state) => state.myaccount.addMyaccount);
  useEffect(() => {
    if (showCartPopup) {
      const timer = setTimeout(() => {
        setShowCartPopup(false);
      }, 2000);

      return () => clearTimeout(timer);
    }
  }, [showCartPopup]);
  const discount =
    Number(mrp) > Number(priceText)
      ? (((Number(mrp) - Number(priceText)) / Number(mrp)) * 100).toFixed(0)
      : 0;

  return (
    <>
      <section className="Product_Info_Card_Section">
        <div className="Product_Info_Card">
          <div className="upper_image_section">
            <Link
              href={`/product-details/${encodeId(product?.id)}?qty=${quantity}`}
            >
              <div className="card_img_holder">
                <img className="" src={imgSrc} alt={productName} />
              </div>
            </Link>

            <div className="text_div">
              {/* <div className="discont_div">
                {isOutOfStock && (
                  <p className={`discount_text`}>Out of Stock</p>
                )}
              </div> */}

              {discount > 0 && (
                <div className="discont_div">
                  <p className="discount_text">{discount}% Off</p>
                </div>
              )}
              {product?.company && (
                <div className="company_div">
                  <p className="company_text">{product?.company}</p>
                </div>
              )}
            </div>
          </div>

          <div className="lower_text_section">
            <p
              className="product_name"
              onClick={() => {
                navigate.push(
                  `/product-details/${encodeId(product?.id)}?qty=${quantity}`,
                );
              }}
            >
              {productName}
            </p>

            <div className="pricing_div">
              <div className="left_side">
                <p className="selling_price">
                  ₹
                  {isSignin &&
                  Number(user?.role_id) === Number(RoleId.B2BCustomer)
                    ? variant?.b2b_price
                    : variant?.price}
                </p>{" "}
                <p className="mrp">
                  ₹
                  {isSignin &&
                  Number(user?.role_id) === Number(RoleId.B2BCustomer)
                    ? variant?.b2b_mrp
                    : variant?.mrp}
                </p>{" "}
                <span className="gst-inc">incl. GST</span>
              </div>
            </div>

            <div className="text-center btn_holder">
              {isOutOfStock ? (
                <div className="out-stock-wrapper">
                  <p className="out-stock-statusss">Out of Stock</p>
                </div>
              ) : (
                <>
                  {cartItem ? (
                    <>
                      {" "}
                      <Increment_decrement_btn_holder_add
                        // quantity={displayQty}
                        quantity={quantity}
                        setQuantity={setQuantity}
                        val={cartItem}
                        setError={setStockError}
                        setInstock={setInStock}
                        stock={stock}
                        isCart={false}
                      />
                      {/* <Add_to_card_btn
                        id={product?.id}
                        product={product}
                        // quantity={displayQty}
                        quantity={quantity}
                        setQuantity={setQuantity}
                        stock={stock}
                        cartItem={cartItem}
                        inStock={inStock}
                        isProductCard={true}
                        onAdded={() => setShowCartPopup(true)}
                      /> */}
                    </>
                  ) : (
                    <Add_to_card_btn
                      id={product?.id}
                      product={product}
                      // quantity={displayQty}
                      quantity={quantity}
                      setQuantity={setQuantity}
                      stock={stock}
                      cartItem={cartItem}
                      inStock={inStock}
                      isProductCard={true}
                      onAdded={() => setShowCartPopup(true)}
                    />
                  )}
                </>
              )}
            </div>
            {/* {inStock && stockError && (
              <p className="out-stock-status text-danger">{stockError}</p>
            )} */}
            <Best_seller_heart product={product} />
          </div>
        </div>
      </section>

      <Modal
        show={showCartPopup}
        onHide={() => setShowCartPopup(false)}
        dialogClassName="cart-toast-modal"
        centered={false}
        className="cart-popup-modal"
      >
        <Modal.Body>
          <div className="cart-toast-content">
            <img
              src={imgSrc}
              alt={productName}
              className="toast-product-image"
            />

            <div className="toast-details">
              <h5>{productName}</h5>
              <p>Added to cart successfully.</p>

              <div className="toast-btns">
                <button
                  className="continue-btn"
                  onClick={() => setShowCartPopup(false)}
                >
                  Continue
                </button>

                <button
                  className="view-cart-btn"
                  onClick={() => {
                    setShowCartPopup(false);
                    navigate.push("/product-cart/");
                  }}
                >
                  View Cart
                </button>
              </div>
            </div>
          </div>
        </Modal.Body>
      </Modal>
      <Modal
        show={showStockErrorPopup}
        onHide={() => {
          setShowStockErrorPopup(false);
          setStockError("");
        }}
        centered
        className="stock-error-popup"
      >
        <Modal.Body>
          <div className="stock-error-content">
            <div className="stock-error-icon">
              <span>!</span>
            </div>

            <div className="stock-error-text">
              <h5>Stock Limit Reached</h5>
              <p>{stockError}</p>
            </div>

            <button
              type="button"
              className="stock-error-close-btn"
              onClick={() => {
                setShowStockErrorPopup(false);
                setStockError("");
              }}
            >
              Okay
            </button>
          </div>
        </Modal.Body>
      </Modal>
    </>
  );
};

export default Product_Info_Card;
