import React, { useEffect, useState } from "react";
import "./Product_info.css";
import Green_btn from "../../common-components/common_btn/green_btn/Green_btn";

import Rating from "react-rating";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faStar as farStar } from "@fortawesome/free-regular-svg-icons";
import { faStar as fasStar } from "@fortawesome/free-solid-svg-icons";
import "swiper/css";
import { useDispatch, useSelector } from "react-redux";
import { getAllCart, postCart } from "../../../features/cart/cartSlice";
import { RoleId, variant_type } from "../../../utils/common";
import { useRouter } from "next/navigation";
import Increment_decrement_btn_holder_add from "../../common-components/common_btn/increment_decrement_btn_holder/Increment_decrement_btn_holder_add";

const Product_info = ({
  selectedVariant,
  setSelectedVariant,
  activeSize,
  activeTriple,
  activeMetal,
  setActiveTriple,
  setActiveSize,
  setActiveMetal,
  product,
  avg_rating,
  qty,
}) => {
  const navigate = useRouter();

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

  const dispatch = useDispatch();

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

  const isSignIn = useSelector((state) => state.auth.is_signin);
  const addToCart = async () => {
    try {
      const data = {
        product_id: product.id,
        variant_type_id: product.variant_type_id,

        // variant_id: selectedVariant?.id,
        quantity: quantity,
      };
      if (Number(product.variant_type_id) === variant_type.Single) {
        data.variant_id = selectedVariant?.id;
      } else if (Number(product.variant_type_id) === variant_type.Double) {
        data.d_variant_id = selectedVariant?.id;
      } else if (Number(product.variant_type_id) === variant_type.Triple) {
        data.t_variant_id = selectedVariant?.id;
      }
      const res = await dispatch(postCart({ data: data, isSignIn: isSignIn }));

      if (res.meta?.requestStatus === "fulfilled") {
        handleClick();
        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);
    }
  };

  // Auto select first available variant
  useEffect(() => {
    if (
      Number(product?.variant_type_id) === Number(variant_type.Double) &&
      activeMetal?.Double_Variants?.length > 0
    ) {
      setSelectedVariant(activeMetal?.Double_Variants?.[0]);
      setActiveSize(activeMetal?.Double_Variants?.[0]);
    }
  }, [activeMetal]);

  useEffect(() => {
    if (
      Number(product?.variant_type_id) === Number(variant_type.Triple) &&
      setActiveSize?.Triple_Variants?.length > 0
    ) {
      setSelectedVariant(setActiveSize?.Triple_Variants?.[0]);
      setActiveTriple(setActiveSize?.Triple_Variants?.[0]);
    }
  }, [setActiveSize]);

  const currentCurrency = useSelector((state) => state.master.currentCurrency);
  const rate = Number(currentCurrency?.rate) || 1;
  const symbol = currentCurrency?.symbol || "₹";
  const isSignin = useSelector((state) => state.auth.is_signin);
  const user = useSelector((state) => state.myaccount.addMyaccount);
  const cartItems = useSelector((state) => state.cart.allCarts.data || []);
  useEffect(() => {
    dispatch(getAllCart(isSignin));
  }, [dispatch]);
  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 [inStock, setInStock] = useState(false);
  const stock = Number(selectedVariant?.general_stock || 0);
  const [stockError, setStockError] = useState("");
  return (
    <section className="Product_info">
      <div className="text_holder">
        <div className="head-wrapper">
          <h4 className="">{product?.name}</h4>
          <div className="rating_holder">
            <p className="rating_text ">
              <Rating
                className="star_icons "
                initialRating={Number(avg_rating?.average_rating)}
                emptySymbol={<FontAwesomeIcon icon={farStar} color="#fff" />}
                fullSymbol={<FontAwesomeIcon icon={fasStar} color="#fff" />}
                fractions={2}
                readonly
              />
              {Number(avg_rating?.average_rating)} | {avg_rating?.total_counts}{" "}
              Reviews
            </p>
          </div>
        </div>
        {selectedVariant && (
          <div className="price_holder">
            <h6 className="">
              {symbol}{" "}
              {isSignin && Number(user?.role_id) === Number(RoleId.B2BCustomer)
                ? Number(selectedVariant.b2b_price).toFixed(2)
                : Number(selectedVariant.price).toFixed(2)}
              <span className="discounted_price">
                {symbol}{" "}
                {isSignin &&
                Number(user?.role_id) === Number(RoleId.B2BCustomer)
                  ? Number(selectedVariant.b2b_mrp).toFixed(2)
                  : Number(selectedVariant.mrp).toFixed(2)}
              </span>
            </h6>
            <div className="save_div">
              <Green_btn
                btnText={`Save: ${
                  Math.round(
                    ((selectedVariant.mrp * rate -
                      selectedVariant.price * rate) /
                      (selectedVariant.mrp * rate)) *
                      100,
                  ) || 0
                }%`}
              />
            </div>

            <span className="mrp_holder">
              MRP (Inclusive of all taxes and GST)
            </span>
          </div>
        )}
      </div>

      <div>
        {/* METAL */}

        <div className="quantity_holder">
          <div className="product_meta_info">
            <p className="details">
              <span>Brand:</span> {product?.Brand?.name}
            </p>

            <p className="details">
              <span>Category:</span> {product?.p_category?.name}
            </p>

            <p className="details">
              <span>Sub Category:</span> {product?.p_sub_category?.name}
            </p>
          </div>
        </div>

        <p>
          {/* <strong>Measurement</strong> : {product?.measurements}{" "} */}
        </p>

        {/* TRIPLE VARIANTS */}
        {product?.Product_Variants?.find(
          (v) => v.id === activeMetal?.id,
        )?.Double_Variants?.find((s) => s.id === activeSize?.id)
          ?.Triple_Variants?.length > 0 &&
          Number(product?.variant_type_id) === Number(variant_type.Triple) && (
            <div className="quantity_holder">
              <p className="type_text">Diamond</p>
              <div className="row">
                {product.Product_Variants.find((v) => v.id === activeMetal?.id)
                  .Double_Variants.find((s) => s.id === activeSize?.id)
                  .Triple_Variants.map((item1) => (
                    <div className="col-sm-3 col-6 mb-3" key={item1.id}>
                      <div
                        className={`quantity_box_holder ${
                          activeTriple?.id === item1.id ? "active" : ""
                        }`}
                        onClick={() => {
                          setActiveTriple(item1);
                          if (
                            product?.variant_type_id === variant_type.Triple
                          ) {
                            setSelectedVariant(item1);
                          }
                        }}
                      >
                        <div className="info_holder">
                          <h5>{item1?.Diamond?.name}</h5>
                        </div>
                      </div>
                    </div>
                  ))}
              </div>
            </div>
          )}
      </div>

      <div className="prod_description"></div>

      <div className="btn_holder ">
        <div className="add_cart_btn">
          {selectedVariant?.general_stock <= 0 ? (
            <Green_btn
              btnText="Out of Stock"
              product={product}
              // onClick={addToCart}
              quantity={quantity}
              setQuantity={setQuantity}
              selectedVariant={selectedVariant}
            />
          ) : (
            <div className="d-flex gap-3">
              <Increment_decrement_btn_holder_add
                quantity={quantity}
                setQuantity={setQuantity}
                val={cartItem}
                setError={setStockError}
                setInstock={setInStock}
                stock={stock}
                isCart={false}
              />

              {cartItem ? (
                <Green_btn
                  btnText="View In Cart"
                  product={product}
                  onClick={handleClick}
                  quantity={quantity}
                  setQuantity={setQuantity}
                  selectedVariant={selectedVariant}
                />
              ) : (
                <Green_btn
                  btnText="Add to Cart"
                  product={product}
                  onClick={addToCart}
                  quantity={quantity}
                  setQuantity={setQuantity}
                  selectedVariant={selectedVariant}
                />
              )}
              {inStock && stockError && (
                <p className="out-stock-status text-danger">{stockError}</p>
              )}
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

export default Product_info;
