import React, { useEffect, useState } from "react";
import "./Product_info.css";
import Green_btn from "../../common-components/common_btn/green_btn/Green_btn";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import Rating from "react-rating";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faStar as farStar } from "@fortawesome/free-regular-svg-icons";
import {
  faCartShopping,
  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 { 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,
}) => {
  const navigate = useRouter();

  const dispatch = useDispatch();

  const [quantity, setQuantity] = useState(1);
  const [instock, setInstock] = useState(false);
  const [error, setError] = useState("");

  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,
        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") {
        await dispatch(getAllCart(isSignIn)); // refresh so cartItem picks it up
      } else if (res.meta?.requestStatus === "rejected") {
        console.log("Error:", res.payload || "Not In Cart");
      }
    } catch (error) {
      console.log("Error:", error);
    }
  };

  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) &&
      activeSize?.Triple_Variants?.length > 0
    ) {
      const firstDiamond = activeSize.Triple_Variants[0];
      setSelectedVariant(firstDiamond);
      setActiveTriple(firstDiamond);
    }
  }, [activeSize]);

  const currentCurrency = useSelector((state) => state.master.currentCurrency);
  const rate = Number(currentCurrency?.rate) || 1;
  const symbol = currentCurrency?.symbol || "₹";

  useEffect(() => {
    if (!activeMetal && product?.Product_Variants?.length > 0) {
      const firstColour = product.Product_Variants[0];
      setActiveMetal(firstColour);
      if (Number(product?.variant_type_id) === Number(variant_type.Single)) {
        setSelectedVariant(firstColour);
      }
    }
  }, [product]);

  const cartData = useSelector((state) => state?.cart?.allCarts);

  const cartItem = cartData?.data?.find((val) => {
    if (Number(val?.product_id) !== Number(product?.id)) return false;

    if (Number(product?.variant_type_id) === Number(variant_type.Single)) {
      return Number(val?.variant_id) === Number(selectedVariant?.id);
    } else if (
      Number(product?.variant_type_id) === Number(variant_type.Double)
    ) {
      return Number(val?.d_variant_id) === Number(selectedVariant?.id);
    } else if (
      Number(product?.variant_type_id) === Number(variant_type.Triple)
    ) {
      return Number(val?.t_variant_id) === Number(selectedVariant?.id);
    }
    return false;
  });

  let stock;
  let isInstock = false;
  if (cartItem) {
    if (
      Number(cartItem?.Product?.variant_type_id) === Number(variant_type.Single)
    ) {
      stock = Number(cartItem?.Product_Variant?.general_stock);
    } else if (
      Number(cartItem?.Product?.variant_type_id) === Number(variant_type.Double)
    ) {
      stock = Number(cartItem?.Double_Variant?.stock);
    } else if (
      Number(cartItem?.Product?.variant_type_id) === Number(variant_type.Triple)
    ) {
      stock = Number(cartItem?.Triple_Variant?.stock);
    }
    isInstock = stock <= cartItem?.quantity;
  }

  let selectedStock = 0;

  if (Number(product?.variant_type_id) === Number(variant_type.Single)) {
    selectedStock = Number(selectedVariant?.general_stock || 0);
  } else if (Number(product?.variant_type_id) === Number(variant_type.Double)) {
    selectedStock = Number(selectedVariant?.stock || 0);
  } else if (Number(product?.variant_type_id) === Number(variant_type.Triple)) {
    selectedStock = Number(selectedVariant?.stock || 0);
  }

  return (
    <section className="Product_info">
      <div className="text_holder">
        <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>
        {selectedVariant && (
          <div className="price_holder">
            <h6 className="">
              {symbol} {Number(selectedVariant.price * rate).toFixed(2)}{" "}
              <span className="discounted_price">
                {symbol} {Number(selectedVariant.mrp * rate).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)</span>
          </div>
        )}

        {product?.is_returnable ? (
          <p className="return-option-text">
            <span>✓ </span>Returnable
          </p>
        ) : (
          <p className="return-option-text not-return">
            <span>✕ </span> Non-returnable
          </p>
        )}
      </div>

      <div>
        {/* METAL */}

        <div className="color_swiper_holder quantity_holder">
          {/* <p className="type_text">Colour</p> */}
          <p className="type_text">{product?.variant_name}</p>

          <Swiper
            slidesPerView={6.5}
            spaceBetween={10}
            breakpoints={{
              0: { slidesPerView: 4.2 },
              400: { slidesPerView: 4.8 },
              500: { slidesPerView: 3.3 },
              768: { slidesPerView: 3.5 },
              830: { slidesPerView: 4 },
              992: { slidesPerView: 5 },
              1200: { slidesPerView: 8.5 },
            }}
            className="Product_details_Swiper_holder"
          >
            {product?.Product_Variants?.map((option) => {
              const swatchImage = option?.Product_Images?.[0]?.image;
              const isActive = activeMetal?.id === option.id;
              const isSingle =
                Number(product?.variant_type_id) ===
                Number(variant_type.Single);

              return (
                <SwiperSlide key={option.id}>
                  <div
                    className={`${
                      isSingle ? "quantity_box_holder" : "color_img_holder"
                    } ${isActive ? "active" : ""}`}
                    onClick={() => {
                      setActiveMetal(option);
                      if (isSingle) {
                        setSelectedVariant(option);
                      }
                    }}
                  >
                    {isSingle ? (
                      <div className="info_holder">
                        <h5>{option?.Metal?.name}</h5>
                      </div>
                    ) : (
                      swatchImage && (
                        <img
                          className="Product_img"
                          src={process.env.NEXT_PUBLIC_IMG_URL + swatchImage}
                        />
                      )
                    )}
                  </div>
                </SwiperSlide>
              );
            })}
          </Swiper>
        </div>

        {/* <br></br> */}

        {/* SIZE (Double Variants) */}
        {product?.Product_Variants?.find((v) => v.id === activeMetal?.id)
          ?.Double_Variants?.length > 0 && (
          <div className="quantity_holder">
            <p className="type_text">Size</p>
            <div className="d-flex flex-wrap">
              {product.Product_Variants.find(
                (v) => v.id === activeMetal?.id,
              ).Double_Variants.map((item) => (
                <div className="sizebox  me-2" key={item.id}>
                  <div
                    className={`quantity_box_holder ${
                      activeSize?.id === item.id ? "active" : ""
                    }`}
                    onClick={() => {
                      setActiveSize(item);
                      // setActiveTriple(null);
                      if (product?.variant_type_id === variant_type.Double) {
                        setSelectedVariant(item);
                      }
                    }}
                  >
                    <div className="info_holder">
                      <h5>{item?.Size?.name}</h5>
                    </div>
                  </div>
                </div>
              ))}
            </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">
          {selectedStock <= 0 ? (
            <Green_btn btnText="Out of Stock" />
          ) : cartItem ? (
            <>
              <Increment_decrement_btn_holder_add
                val={cartItem}
                quantity={cartItem.quantity}
                setInstock={setInstock}
                setError={setError}
                error={error}
                isInstock={isInstock}
              />
              {isInstock && error && (
                <p
                  style={{ color: "red", textAlign: "center", margin: "5px 0" }}
                >
                  {`Only ${stock} quantity in stock`}
                </p>
              )}
            </>
          ) : (
            <Green_btn
              btnText={
                <>
                  <FontAwesomeIcon icon={faCartShopping} /> Add to Cart
                </>
              }
              onClick={addToCart}
            />
          )}
        </div>
      </div>
    </section>
  );
};

export default Product_info;
