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 { postCart } from "../../../features/cart/cartSlice";
import { variant_type } from "../../../utils/common";
import { useRouter } from "next/navigation";

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

  const navigate = useRouter();

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

  const dispatch = useDispatch();

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

  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 || "₹";

  // console.log(selectedVariant, "selectedVariant selectedVariant uuuuuu");

  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}
            />
            {Number(avg_rating?.average_rating)} | {avg_rating?.total_counts}{" "}
            Reviews
          </p>
        </div>
        {selectedVariant && (
          <div className="price_holder">
            <h6 className="">
              <span className="discounted_price">
                {symbol} {Number(selectedVariant.mrp * rate).toFixed(2)}
              </span>
              {symbol} {Number(selectedVariant.price * rate).toFixed(2)}
            </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>
        )}
      </div>

      <div>
        {/* METAL */}

        <div className="quantity_holder">
          <p className="type_text">Variant</p>
          <div className="d-flex flex-wrap">
            {product?.Product_Variants?.map((option) => (
              <div className="me-1" key={option.id}>
                <div
                  // className={`quantity_box_holder${
                  //   Number(selectedVariant?.id) === Number(option.id)
                  //     ? "active"
                  //     : ""
                  // }`}
                  className={`quantity_box_holder ${
                    Number(option?.general_stock) <= 0
                      ? "prodnotavailable"
                      : activeMetal?.id === option.id
                      ? "active"
                      : ""
                  }`}
                  onClick={() => {
                    setActiveMetal(option);
                    if (
                      Number(product?.variant_type_id) ===
                      Number(variant_type.Single)
                    ) {
                      setSelectedVariant(option);
                    }
                  }}
                >
                  <div className="info_holder">
                    <h5>{option?.Metal?.name}</h5>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </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 mb-3 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="quantity_holder">
        <div className="row">
          {product?.Product_Variants?.map((option, index) => (
            <>
              <div
                className="col-sm-4 col-6 mb-3"
                key={index}
                onClick={() => {
                  setActiveIndex(index);
                  // setselectedVariant(option?.variant);
                }}
              >
                <div
                  className={`quantity_box_holder ${
                    index === activeIndex ? "active" : ""
                  }`}
                >
                  <div className="info_holder">
                    <h5>{option?.Metal?.name}</h5>
                 
                  </div>
                </div>
              </div>

              {option?.Double_Variants?.map((item, dindex) => {
                <>
                  <div className="quantity_holder">
                    <p className="type_text">Diamond</p>

                    <div className="row">
                      <div className="col-sm-3 col-6 mb-3">
                        <div
                          className={`quantity_box_holder ${
                            dindex === activeIndex2 ? "active" : ""
                          }`}
                          onClick={() => {
                            setActiveIndex2(dindex);
                            // setselectedVariant(item?.variant);
                          }}
                        >
                          <div className="info_holder">
                            <h5>{item?.Size?.name}</h5>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="quantity_holder">
                    <p className="type_text">Size</p>

                    <div className="size_holder">
                      {item?.Triple_Variants?.map((item1, tindex) => {
                        return (
                          <div className="size_box">
                            <div
                              className={`quantity_box_holder ${
                                tindex === activeIndex2 ? "active" : ""
                              }`}
                              onClick={() => {
                                setActiveIndex2(tindex);
                                // setselectedVariant(item);
                              }}
                            >
                              <div className="info_holder">
                                <h5>{item1?.Diamond?.name}</h5>
                              </div>
                            </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}
            />
          ) : (
            <Green_btn
              btnText="Add to Cart"
              product={product}
              onClick={addToCart}
              quantity={quantity}
              setQuantity={setQuantity}
              selectedVariant={selectedVariant}
            />
          )}
        </div>
      </div>
    </section>
  );
};

export default Product_info;
