import React, { useEffect, useState } from "react";
import { Footer } from "../../../layouts/footer";
import ResponsiveAppBar from "../../../layouts/navbar";
import { PeopleAlsoBought } from "./components/PeopleAlsoBought";
import { RecentlyViewed } from "./components/RecentlyViwed";
import { useAppDispatch, useAppSelector } from "../../../../app/redux/hooks";
import { getDecryptedToken } from "../../../../app/auth/authHandler";
import {
  addReviewAsync,
  editReviewAsync,
  getProductDescriptionWithCategoryAsync,
  removeReviewAsync,
} from "../../../../app/slices/productDiscriptionSlice/ProductDescriptionSlice";
import { DescriptionSwiper } from "./components/DescriptionSwiper";

import { Button, CircularProgress, Tooltip } from "@mui/material";
import { ProductValues, SkuValues } from "./productDescriptionTypes";
import {
  addOrUpdateCartAsync,
  fetchCartListAsync,
  removeItemFromCartAsync,
} from "../../../../app/slices/cartSlice/CartSlice";
import CustomButton from "../../../components/custom/button";
import { showSnackbar } from "../../../../app/slices/common/customSnackBar/customSnackbarSlice";
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
import WhatsAppIcon from "@mui/icons-material/WhatsApp";
import ConfirmationDialog from "../../../components/custom/confirm";
import moment from "moment";
import {
  addToWisshListAsync,
  removeFromWishListAsync,
} from "../../../../app/slices/wishlistSlice/wishlistSlice";

export const ProductDescriptionPage = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const { productId } = useParams(); // Get product_id from URL
  const [editingIndex, setEditingIndex] = useState<number | any>(null);
  const [deletingIndex, setDeletingIndex] = useState<number | any>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editedReview, setEditedReview] = useState<any>({
    review_heading: "",
    review_text: "",
    rating: 5,
  });
  const [activeTab, setActiveTab] = React.useState("Description");
  const location = useLocation();
  const [isQuantityLoading, setIsQuantityLoading] = useState(false);
  const [isDataExist, setIsDataExist] = useState(true);
  const handleTabClick = (tab: any) => {
    setActiveTab(tab);
  };

  // Helper function to check if product_description has any non-empty values
  const hasProductDescriptionContent = () => {
    if (!productData?.product_description) return false;
    const desc = productData.product_description;
    return (
      (desc.Ingredients && desc.Ingredients.trim() !== "") ||
      (desc["Nutritional Info"] && desc["Nutritional Info"].trim() !== "") ||
      (desc["Allergen Description"] && desc["Allergen Description"].trim() !== "") ||
      (desc["Allergen Info"] && desc["Allergen Info"].trim() !== "") ||
      (desc["Additional Info"] && desc["Additional Info"].trim() !== "")
    );
  };

  const [reviews, setReviews] = useState<any>([]);
  const [currentUserUuid, setCurrentUserId] = useState<any>([]);
  const [productData, setProductData] = useState<ProductValues | null>(null);

  const [quantities, setQuantities] = useState<{ [skuId: number]: number }>({});
  const [selectedSku, setSelectedSku] = useState<SkuValues | null>(null);
  const [action, setAction] = useState("Add");
  const [addReview, setAddReview] = useState(false);
  const [whatsappLink, setWhatsappLink] = useState("");
  const [categoryName, setCategoryName] = useState("");
  const [categoryCode, setCategoryCode] = useState("");
  const { productDescriptionId } = useAppSelector(
    (state) => state.productDescriptionState
  );
  const isLoading = useAppSelector(
    (state) => state.productDescriptionState.productDescription.loader
  );

  const { addTocart } = useAppSelector((state) => state.CartState);
  const cartData = addTocart?.data;

  const categories = useAppSelector(
    (state) => state.productTypesState.productTypes
  );

  useEffect(() => {
    // Disable browser's default scroll restoration
    if ("scrollRestoration" in window.history) {
      window.history.scrollRestoration = "manual";
    }

    // Scroll to top on location change
    window.scrollTo(0, 0);

    // Reset scroll restoration on unmount (optional)
    return () => {
      if ("scrollRestoration" in window.history) {
        window.history.scrollRestoration = "auto";
      }
    };
  }, [location]);

  useEffect(() => {
    let code = localStorage.getItem("Category_code");
    if (code && categories && categories.data) {
      setCategoryCode(code);
      const foundCategory = categories.data.find(
        (category: { category_code: string; category_name: string }) =>
          category.category_code === code
      );
      if (foundCategory) {
        setCategoryName(foundCategory.category_name);
      }
    }
  }, [categories]);
//  const hasFetched = React.useRef(false);
 useEffect(() => {
  let product_id;

  if (productId) {
    product_id = productId;
  } else if (productDescriptionId) {
    product_id = productDescriptionId;
  } else {
    product_id = localStorage.getItem("product_id");
  }

  const aId = localStorage.getItem("aId");
  const accessToken = getDecryptedToken();
  const anonymous_id = accessToken ? null : aId || null;

  if (!product_id) return;

  // Reset old data when product changes
  setProductData(null);

  dispatch(
    getProductDescriptionWithCategoryAsync({
      product_id,
      anonymous_id,
    })
  ).then((response: any) => {
    if (response?.payload?.status === 200) {
      const res = response?.payload?.data;

      setProductData(res?.data);
      setReviews(res?.data?.reviews);
      setCurrentUserId(res?.data?.user_id);

      setSelectedSku(
        res?.data?.skus?.find(
          (product: any) => product?.sku_status !== ""
        )
      );

      setIsDataExist(true);
    } else {
      setIsDataExist(false);
    }
  });

  const quantities =
    cartData?.reduce((acc: any, item: any) => {
      acc[item.sku_id] = item.quantity;
      return acc;
    }, {}) || {};

  setQuantities(quantities);
}, [productId, productDescriptionId, editingIndex, addReview, deletingIndex]);

  useEffect(() => {
    const quantities =
      cartData?.reduce((acc: any, item: any) => {
        acc[item.sku_id] = item.quantity;
        return acc;
      }, {}) || {};
    setQuantities(quantities);
  }, [cartData]);
  useEffect(() => {
    const selection = cartData.some(
      (p: any) => p.sku_id === selectedSku?.sku_id
    );
    if (selection) {
      setAction("Update");
    } else {
      setAction("Add");
    }
  }, [selectedSku, cartData]);
  // const handleQuantityChange = (
  //   skuId: number | undefined,
  //   action: "increase" | "decrease"
  // ) => {
  //   if (skuId === undefined) return;
  //   setQuantities((prevQuantities) => {
  //     const currentQuantity = prevQuantities[skuId] || 0;
  //     return {
  //       ...prevQuantities,
  //       [skuId]:
  //         action === "increase"
  //           ? Math.min(
  //               currentQuantity + 1,
  //               selectedSku?.sku_bulk_qty_limit || Infinity
  //             )
  //           : Math.max(currentQuantity - 1, 0),
  //     };
  //   });
  // };

  const handleQuantityChange = async (
    skuId: number | undefined,
    action: "increase" | "decrease"
  ) => {
    if (skuId === undefined) return;

    const cartItem = cartData.find((item: any) => item.sku_id === skuId);
    const cart_item_id = cartItem?.cart_item_id;

    setIsQuantityLoading(true);

    setQuantities((prevQuantities) => {
      const currentQuantity = prevQuantities[skuId] || 0;
      const maxQuantity = Infinity;

      const newQuantity =
        action === "increase"
          ? Math.min(currentQuantity + 1, maxQuantity)
          : Math.max(currentQuantity - 1, 0);

      return {
        ...prevQuantities,
        [skuId]: newQuantity,
      };
    });

    try {
      if (quantities[skuId] === 1 && action === "decrease" && cart_item_id) {
        const response: any = await dispatch(
          removeItemFromCartAsync(cart_item_id)
        );
        if (response?.payload?.status === 200) {
          const aId = localStorage.getItem("aId");
          const accessToken = getDecryptedToken();
          const anonymous_id = accessToken ? null : aId || null;
          await dispatch(fetchCartListAsync(anonymous_id));
        }
      } else {
        const updatedQuantities = {
          ...quantities,
          [skuId]:
            action === "increase"
              ? (quantities[skuId] || 0) + 1
              : Math.max((quantities[skuId] || 0) - 1, 0),
        };

        const payload: any = {
          skus: Object.entries(updatedQuantities).map(([sku, qty]) => ({
            sku: Number(sku),
            quantity: qty,
          })),
        };

        const aId = localStorage.getItem("aId");
        const accessToken = getDecryptedToken();
        if (aId && !accessToken) {
          payload.anonymous_id = aId;
        }

        await dispatch(addOrUpdateCartAsync(payload));
      }
    } catch (error) {
      console.error("Cart update failed:", error);
    } finally {
      setIsQuantityLoading(false); // 🔁 This now runs AFTER dispatch completes
    }
  };

  const calculateTotalAmount = (): number => {
    if (!productData) return 0;
    return productData?.skus?.reduce((total, sku) => {
      const quantity = quantities[sku.sku_id] || 0;
      const price = parseFloat(sku.offer_price) || 0;
      return total + price * quantity;
    }, 0);
  };
  const selectSku = (sku: any) => {
    setSelectedSku(sku);
  };
  let v: any = quantities[selectedSku?.sku_id];

  // const addtocartButtonCall = () => {
  //   const payload: any = {
  //     skus: Object.entries(quantities)?.map(([sku, quantity]) => ({
  //       sku: Number(sku),
  //       quantity,
  //     })),
  //   };
  //   const aId = localStorage.getItem("aId");
  //   const accessToken = localStorage.getItem("accessToken");
  //   if (aId && accessToken == null) {
  //     payload.anonymous_id = aId;
  //   }
  //   dispatch(addOrUpdateCartAsync(payload)).then((response: any) => {
  //     if (response?.payload?.status === 200) {
  //       dispatch(
  //         showSnackbar({
  //           message: "Cart updated succesfuly.",
  //           severity: "success",
  //           autoHide: 2000,
  //         })
  //       );
  //     } else {
  //       dispatch(
  //         showSnackbar({
  //           message: "Please try again later.",
  //           severity: "error",
  //           autoHide: 3000,
  //         })
  //       );
  //     }
  //   });
  // };

  const addtocartButtonCall = () => {
    const mappedSkus = Object.entries(quantities)?.map(([sku, quantity]) => ({
      sku: Number(sku),
      quantity,
    }));
    const payload: any = {
      skus: mappedSkus.filter((item) => {
        if (item.quantity === 0) {
          const cartItem = cartData.find(
            (cartItem: any) => cartItem.sku_id === selectedSku?.sku_id
          );
          const cart_item_id = cartItem?.cart_item_id;
          dispatch(removeItemFromCartAsync(cart_item_id)).then(
            (response: any) => {
              if (response?.payload?.status === 200) {
                const aId = localStorage.getItem("aId");
                const accessToken = getDecryptedToken();
                const anonymous_id = accessToken ? null : aId ? aId : null;
                dispatch(fetchCartListAsync(anonymous_id));
              }
            }
          );
          return false;
        }
        return true;
      }),
    };

    if (payload.skus.length > 0) {
      const aId = localStorage.getItem("aId");
      const accessToken = getDecryptedToken();
      let anonymous_id: any;
      if (aId && !accessToken) {
        anonymous_id = aId;
      }
      payload.anonymous_id = anonymous_id;
      dispatch(addOrUpdateCartAsync(payload)).then((response: any) => {
        if (response?.payload?.status === 200) {
          let product_id;
          if (productDescriptionId) {
            product_id = productDescriptionId;
          } else {
            product_id = localStorage.getItem("product_id");
          }
          // dispatch(getPeopleBaughtListAsync({ anonymous_id, product_id }));
          // setIsEnable(false);
          dispatch(
            showSnackbar({
              message: "Cart updated successfully.",
              severity: "success",
              autoHide: 2000,
            })
          );
        } else {
          dispatch(
            showSnackbar({
              message: "Please try again later.",
              severity: "error",
              autoHide: 3000,
            })
          );
        }
      });
    }
  };

  const isDisabled =
    selectedSku?.sku_id &&
    quantities[selectedSku.sku_id] >= selectedSku.sku_bulk_qty_limit;
  const isDisabledOut =
    selectedSku?.sku_status === "Out of Stock" ||
    selectedSku?.sku_status === "Disabled";

  const handleCancel = () => {
    setEditingIndex(null);
    resetEditedReview();
  };
  const resetEditedReview = () => {
    setEditedReview({
      review_heading: "",
      review_text: "",
      rating: 5,
    });
  };

  const handleAddReview = () => {
    const accessToken = getDecryptedToken();
    if (accessToken) {
      setAddReview(true);
      resetEditedReview();
    } else {
      dispatch(
        showSnackbar({
          message: "Please login to add review",
          severity: "error",
          autoHide: 2000,
        })
      );
    }
  };
  const handleCancelAdd = () => {
    setAddReview(false);
    resetEditedReview();
  };
  const closeDialog = () => {
    setDeletingIndex(null);
    setDialogOpen(false);
  };
  const handleAddToWishList = (productId: any) => {
    const accessToken = getDecryptedToken();
    if (accessToken) {
      addToWishList(productId);
    } else {
      dispatch(
        showSnackbar({
          message: "Please login to create wishlist",
          severity: "error",
          autoHide: 2000,
        })
      );
    }
  };

  const handleRemoveFromWishList = (productId: any) => {
    removeFromWishList(productId);
  };
  const addToWishList = (id: any) => {
    dispatch(addToWisshListAsync(id)).then((response: any) => {
      if (response?.payload?.data) {
        dispatch(
          showSnackbar({
            message: `${response?.payload?.data?.message}`,
            severity: "success",
            autoHide: 2000,
          })
        );
      }
    });
    setProductData((prevProductData) => {
      if (!prevProductData) return prevProductData; // Return if productData is null
      return {
        ...prevProductData,
        wishlist: true, // Update the wishlist property
      };
    });
  };
  const removeFromWishList = (id: any) => {
    dispatch(removeFromWishListAsync(id)).then((response: any) => {
      if (response?.payload?.data) {
        dispatch(
          showSnackbar({
            message: `${response?.payload?.data?.message}`,
            severity: "success",
            autoHide: 2000,
          })
        );
      }
    });
    setProductData((prevProductData) => {
      if (!prevProductData) return prevProductData; // Return if productData is null
      return {
        ...prevProductData,
        wishlist: false, // Update the wishlist property
      };
    });
  };
  const handleSaveAdd = () => {
    if (editedReview.review_heading === "") {
      dispatch(
        showSnackbar({
          message: "Please fill all the fields.",
          severity: "error",
          autoHide: 3000,
        })
      );
      return;
    } else {
      dispatch(
        addReviewAsync({
          product_id: productData?.product_id,
          payload: editedReview,
        })
      ).then((response: any) => {
        if (
          response?.payload?.status === 201 ||
          response?.payload?.status === 200
        ) {
          dispatch(
            showSnackbar({
              message: `${response?.payload?.data?.message}`,
              severity: "success",
              autoHide: 2000,
            })
          );
          if (response?.payload?.data?.status === 1) {
            setAddReview(false);
            resetEditedReview();
          }
        } else {
          dispatch(
            showSnackbar({
              message: "Please try again later.",
              severity: "error",
              autoHide: 3000,
            })
          );
        }
      });
    }
  };
  const handleSaveEdit = () => {
    if (editedReview.review_heading === "" || editedReview.review_text === "") {
      dispatch(
        showSnackbar({
          message: "Please fill all the fields.",
          severity: "error",
          autoHide: 3000,
        })
      );
      return;
    } else {
      dispatch(
        editReviewAsync({
          product_id: editedReview?.review_id,
          payload: editedReview,
        })
      ).then((response: any) => {
        if (
          response?.payload?.status === 201 ||
          response?.payload?.status === 200
        ) {
          dispatch(
            showSnackbar({
              message: `${response?.payload?.data?.message}`,
              severity: "success",
              autoHide: 2000,
            })
          );
          if (response?.payload?.data?.status === 1) {
            // setTimeout(() => {

            setEditingIndex(null);
            setAddReview(false);
            resetEditedReview();
            // }, 2000);
          }
        } else {
          dispatch(
            showSnackbar({
              message: "Please try again later.",
              severity: "error",
              autoHide: 3000,
            })
          );
        }
      });
    }
  };
  const handleDelete = (index: number) => {
    setDeletingIndex(index);

    setDialogOpen(true);
  };
  const confirmAction = () => {
    dispatch(removeReviewAsync(reviews[deletingIndex]?.review_id)).then(
      (response: any) => {
        if (
          response?.payload?.status === 200 ||
          response?.payload?.status === 201
        ) {
          dispatch(
            showSnackbar({
              message: "Review deleted successfuly.",
              severity: "success",
              autoHide: 2000,
            })
          );
          setReviews((prevReviews: any) =>
            prevReviews.filter((_: any, i: any) => i !== deletingIndex)
          );
          closeDialog();
        } else {
          dispatch(
            showSnackbar({
              message: "Please try again later.",
              severity: "error",
              autoHide: 3000,
            })
          );
        }
      }
    );
    closeDialog();
  };

  const handleSave = () => {
    handleSaveEdit();
  };
  const handleEdit = (index: number) => {
    setEditingIndex(index);
    setEditedReview(reviews[index]);
  };
  const percentageDisplay = (offer: any) => {
    if (!offer) {
      return null;
    }
    const percentage = parseFloat(offer.replace("%", ""));

    const formattedPercentage =
      percentage % 1 === 0
        ? `${Math.round(percentage)}%`
        : `${percentage.toFixed(2)}%`;

    return formattedPercentage;
  };
  const totalReviews = reviews.length;
  const ratingCounts = [0, 0, 0, 0, 0]; // Indexes: 0 -> 1★, 1 -> 2★, ..., 4 -> 5★

  reviews.forEach((review: any) => {
    if (review.rating >= 1 && review.rating <= 5) {
      ratingCounts[review.rating - 1]++;
    }
  });

  // Compute average rating (rounded to 1 decimal place)
  const averageRating =
    totalReviews > 0
      ? (
          reviews.reduce((sum: any, review: any) => sum + review.rating, 0) /
          totalReviews
        ).toFixed(1)
      : "0.0";

  // Compute rating percentages
  const ratingPercentages = ratingCounts.map((count) =>
    totalReviews > 0 ? ((count / totalReviews) * 100).toFixed(1) : "0"
  );
  const handleWhatsAppButton = () => {
    const image = productData?.images[0];
    const message = `Check out this awesome product:\nName: ${productData?.product_name}\nPrice: ${selectedSku?.offer_price}\nDescription: ${productData?.item_description}\n${process.env.REACT_APP_DOMAIN_URL}/products/${productData?.product_id}`;

    const encodedMessage = encodeURIComponent(message);
    const whatsappUrl = `https://wa.me/?text=${encodedMessage}`;

    setWhatsappLink(whatsappUrl); // Update state with the new link
  };
  return (
    <>
      <div id="wrapper">
        <ResponsiveAppBar />
        {isDataExist ? (
          <>
            <div className="tf-breadcrumb" key={productId}>
              <div className="container">
                <div className="tf-breadcrumb-wrap d-flex justify-content-between flex-wrap align-items-center">
                  <div className="tf-breadcrumb-list">
                    <a className="text" onClick={() => navigate("/")}>
                      Home
                    </a>
                    {categoryName && (
                      <>
                        <i className="icon icon-arrow-right"></i>
                        <Link
                          to={{
                            pathname: `/product/${categoryCode}`,
                          }}
                        >
                          <span className="text">{categoryName}</span>
                        </Link>
                      </>
                    )}
                    <i className="icon icon-arrow-right"></i>
                    <span className="text">{productData?.product_name}</span>
                  </div>
                </div>
              </div>
            </div>

            <section className="flat-spacing-4 pt_0 pb-5">
              <div
                className="tf-main-product section-image-zoom"
                key={productId}
                style={{ position: "relative" }}
              >
                {isQuantityLoading && (
                  <div
                    className="fade-overlay"
                    style={{
                      position: "absolute",
                      top: 0,
                      left: 0,
                      zIndex: 9999,
                      width: "100%",
                      height: "100%",
                      backgroundColor: "rgba(255, 255, 255, 0.8)",
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "center",
                      alignItems: "center",
                      fontFamily: "Albert Sans, sans-serif",
                    }}
                  >
                    <CircularProgress />
                    <div
                      style={{
                        marginTop: "12px",
                        fontSize: "16px",
                        color: "#333",
                      }}
                    >
                      Updating to Cart...
                    </div>
                  </div>
                )}

                <div
                  className="container"
                  style={{
                    fontFamily: "Albert Sans, sans-serif",
                    opacity: isQuantityLoading ? 0.5 : 1,
                    pointerEvents: isQuantityLoading ? "none" : "auto",
                    transition: "opacity 0.3s ease-in-out",
                  }}
                >
                  {isLoading ? (
                    <div className="row">
                      <div className="col-md-12">
                        <div
                          className="tf-product-media-wrap sticky-top"
                          style={{ minHeight: "50vh" }}
                        >
                          <CircularProgress
                            style={{
                              position: "absolute",
                              top: "50%",
                              left: "50%",
                              transform: "translate(-50%, -50%)",
                            }}
                          />
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div className="row">
                      <div className="col-md-6">
                        <div className="tf-product-media-wrap sticky-top">
                          <DescriptionSwiper productData={productData} />
                        </div>
                      </div>
                      <div className="col-md-6">
                        <div className="tf-product-info-wrap position-relative">
                          <div className="tf-zoom-main"></div>
                          <div className="tf-product-info other-image-zoom">
                            <div style={{ display: "flex", gap: "10px" }}>
                              <div className=" tf-product-info-title">
                                <h5>{productData?.product_name}</h5>
                              </div>
                              <div className="variant-picker-item">
                                <div
                                  className="variant-picker-values"
                                  style={{
                                    display: "flex",
                                    gap: "10px",
                                    paddingTop: "21%", // Removed !important
                                  }}
                                >
                                  <input
                                    id="values-veg"
                                    type="radio"
                                    name="color1"
                                    checked
                                    readOnly
                                  />
                                  <label
                                    className={`hover-tooltip  ${
                                      productData?.product_type === "Veg"
                                        ? "veg"
                                        : "nonveg"
                                    }`}
                                    htmlFor="values-veg"
                                    data-value="Veg"
                                  >
                                    <span
                                      className={`btn-checkbox    ${
                                        productData?.product_type === "Veg"
                                          ? "bg-color-veg bg-veg"
                                          : "bg-color-nonveg "
                                      }`}
                                    ></span>
                                    <span className="tooltip">
                                      {productData?.product_type}
                                    </span>
                                  </label>{" "}
                                </div>
                              </div>
                            </div>

                            {/* lightning symbol commented */}
                            {/* <div className="tf-product-info-badges">
                        <div className="badges">Best seller</div>

                        <div className="product-status-content">
                          <i className="icon-lightning"></i>
                          <p className="fw-6">
                            {productData?.item_description}
                          </p>
                        </div>
                      </div> */}
                            <div className="tf-product-info-price">
                              <div
                                className="price-on-sale"
                                // style={{ marginBottom: "20px" }}
                              >
                                ₹{selectedSku?.offer_price}
                              </div>
                              {/* commented on 12/02  */}

                              {selectedSku?.offer &&
                                selectedSku?.offer !== "0%" && (
                                  <>
                                    <div className="compare-at-price">
                                      ₹{selectedSku?.sku_mrp}
                                    </div>
                                    <div className="badges-on-sale">
                                      <span>
                                        {" "}
                                        {percentageDisplay(selectedSku?.offer)}
                                      </span>{" "}
                                      OFF
                                    </div>
                                  </>
                                )}
                            </div>
                            <div className="mb_20" style={{ marginTop: "4%" }}>
                              {productData?.tags?.map((tag: any) => (
                                <>
                                  <span className="tag label label-info ms-0">
                                    <span>{tag.name}</span>
                                    {/* <a> */}
                                    <span style={{ margin: "1%" }}>
                                      <i className="remove fa fa-check"></i>
                                    </span>
                                    {/* </a> */}
                                  </span>
                                </>
                              ))}
                            </div>
                            <div className="tf-product-info-variant-picker">
                              <div className="variant-picker-item">
                                <div className="d-flex justify-content-between align-items-center">
                                  <div className="variant-picker-label">
                                    {selectedSku?.sku_name}
                                    {/* Weight:{" "}
                              <span className="fw-6 variant-picker-label-value">
                                {selectedSku?.sku_quantity +
                                  selectedSku?.sku_unit}
                              </span> */}
                                  </div>
                                </div>{" "}
                                <div className="variant-picker-values">
                                  {productData?.skus?.map(
                                    (sku: any, index: any) => {
                                      return (
                                        <div id="values-s" key={index}>
                                          <Button
                                            onClick={() => selectSku(sku)}
                                            disabled={
                                              sku?.sku_status ===
                                                "Out of Stock" ||
                                              sku?.sku_status === "Disabled"
                                            }
                                            variant={
                                              selectedSku === sku
                                                ? "contained"
                                                : "outlined"
                                            }
                                            className="style-text"
                                          >
                                            {sku.sku_quantity + sku?.sku_unit}
                                          </Button>
                                        </div>
                                      );
                                    }
                                  )}{" "}
                                </div>
                              </div>

                              <div className="variant-picker-item">
                                {/* Same Day Delivery Message */}
                                {selectedSku?.same_day_delivery === false && (
                                  <div style={{ color: "#00b853", fontSize: "14px", marginBottom: "12px" }}>
                                    Same day delivery will not be available
                                  </div>
                                )}

                                {/* Quantity Picker */}

                                <div className="tf-product-info-quantity">
                                  <div className="quantity-title fw-6">
                                    Quantity
                                  </div>
                                  <div className="wg-quantity">
                                    <Button
                                      className="btn-quantity minus-btn"
                                      onClick={() =>
                                        handleQuantityChange(
                                          selectedSku?.sku_id,
                                          "decrease"
                                        )
                                      }
                                      disabled={isDisabledOut || (quantities[selectedSku?.sku_id] || 0) === 0}
                                    >
                                      -
                                    </Button>
                                    <input
                                      type="text"
                                      value={
                                        selectedSku?.sku_id
                                          ? quantities[selectedSku.sku_id] || 0
                                          : 0
                                      }
                                      readOnly
                                    />
                                    <span className="nav-icon-item">
                                      <Tooltip
                                        title={
                                          isDisabled
                                            ? "You have reached the bulk quantity limit"
                                            : ""
                                        }
                                        placement="top"
                                        arrow
                                        open={isDisabled}
                                      >
                                        <span>
                                          <Button
                                            className="btn-quantity plus-btn"
                                            // style={{
                                            //   background:
                                            //     selectedSku?.sku_id &&
                                            //     quantities[selectedSku.sku_id] >=
                                            //       selectedSku.sku_bulk_qty_limit
                                            //       ? "gray"
                                            //       : "inherit",
                                            // }}
                                            onClick={() =>
                                              // selectedSku?.sku_id &&
                                              // quantities[selectedSku?.sku_id] <
                                              //   selectedSku?.sku_id &&
                                              // selectedSku?.sku_bulk_qty_limit &&
                                              handleQuantityChange(
                                                selectedSku?.sku_id &&
                                                  selectedSku?.sku_id,
                                                "increase"
                                              )
                                            }
                                            disabled={
                                              isDisabled || isDisabledOut
                                            }
                                          >
                                            +
                                          </Button>
                                        </span>
                                      </Tooltip>
                                    </span>
                                  </div>
                                </div>
                              </div>

                              {/* Total Price Display */}
                              <div className="tf-product-info-buy-button">
                                <form className="">
                                  <div
                                    className="d-flex justify-content-start flex-grow-1"
                                    style={{ marginBottom: "5px" }}
                                  >
                                    <Button
                                      style={{
                                        background: "transparent",
                                        fontSize: "18px",
                                        color: "#000",
                                        justifyContent: "start",
                                        paddingLeft: "0px",
                                        cursor: "default",
                                      }}
                                      size="medium"
                                      disabled={
                                        (quantities[selectedSku?.sku_id] ===
                                          0 ||
                                          quantities[selectedSku?.sku_id] ===
                                            undefined) &&
                                        !cartData.some(
                                          (item: { sku_id: any }) =>
                                            item.sku_id === selectedSku?.sku_id
                                        )
                                      }
                                      onClick={addtocartButtonCall}
                                      // Check if your Button component supports loader
                                      // loader={addTocart?.loader}
                                    >
                                      {`Sub Total :₹\u00A0${calculateTotalAmount().toFixed(
                                        2
                                      )}`}
                                    </Button>
                                  </div>
                                  <a
                                    onClick={(e: any) => {
                                      e.preventDefault();
                                      if (productData?.wishlist !== true) {
                                        handleAddToWishList(
                                          productData?.product_id
                                        );
                                      } else {
                                        handleRemoveFromWishList(
                                          productData?.product_id
                                        );
                                      }
                                    }}
                                    className="tf-product-btn-wishlist hover-tooltip box-icon bg_white wishlist btn-icon-action"
                                  >
                                    <span className="tooltip">
                                      {productData?.wishlist !== true
                                        ? "Add to Wishlist"
                                        : "  Remove from Wishlist"}
                                    </span>
                                    {productData?.wishlist !== true ? (
                                      <span className="icon fa-regular fa-heart"></span>
                                    ) : (
                                      <span
                                        style={{ color: "red" }}
                                        className="icon fa-solid fa-heart"
                                      ></span>
                                    )}
                                  </a>

                                  <a
                                    onClick={handleWhatsAppButton}
                                    href={whatsappLink}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                  >
                                    <WhatsAppIcon
                                      style={{ fontSize: 40, color: "#25D366" }}
                                    />
                                  </a>
                                  <div className="w-100">
                                    <button
                                      style={{ 
                                        border: "none",
                                        backgroundColor: (quantities[selectedSku?.sku_id] === 0 || quantities[selectedSku?.sku_id] === undefined || cartData?.length === 0) ? "#cccccc" : "",
                                        color: (quantities[selectedSku?.sku_id] === 0 || quantities[selectedSku?.sku_id] === undefined || cartData?.length === 0) ? "#666666" : "",
                                        cursor: (quantities[selectedSku?.sku_id] === 0 || quantities[selectedSku?.sku_id] === undefined || cartData?.length === 0) ? "not-allowed" : "pointer",
                                        opacity: (quantities[selectedSku?.sku_id] === 0 || quantities[selectedSku?.sku_id] === undefined || cartData?.length === 0) ? "0.6" : "1",
                                      }}
                                      disabled={
                                        quantities[selectedSku?.sku_id] === 0 ||
                                        quantities[selectedSku?.sku_id] ===
                                          undefined ||
                                        cartData?.length === 0
                                      }
                                      onClick={() => navigate("/checkout")}
                                      className="btns-full"
                                    >
                                      Proceed to checkout
                                      {/* <img src="/images/payments/gpay.svg" alt="" /> */}
                                    </button>
                                    {/* <a
                                onClick={() => navigate("/checkout")}
                                className="btns-full"
                              >
                                Buy with{" "}
                                <img src="/images/payments/gpay.svg" alt="" />
                              </a> */}
                                  </div>
                                </form>
                              </div>
                            </div>
                          </div>
                          <div className="tf-product-info-trust-seal">
                            <div className="tf-product-trust-mess">
                              <i className="icon-safe"></i>
                              <p className="fw-6">
                                Guarantee Safe <br /> Checkout
                              </p>
                            </div>
                            <div className="tf-payment">
                              <img src="/shopnow/images/payments/visa.png" alt="" />
                              <img src="/shopnow/images/payments/img-1.png" alt="" />
                              <img src="/shopnow/images/payments/img-2.png" alt="" />
                              <img src="/shopnow/images/payments/img-3.png" alt="" />
                              <img src="/shopnow/images/payments/img-4.png" alt="" />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </section>
            {productData?.item_description && (
              <section className="flat-spacing-17 pt_0">
                <div className="container">
                  <div className="row">
                    <div className="col-12">
                      <div className="widget-tabs style-has-border">
                        <ul className="widget-menu-tab">
                          <li
                            className={`item-title ${
                              activeTab === "Description" ? "active" : ""
                            }`}
                            onClick={() => handleTabClick("Description")}
                          >
                            <span className="inner">Description</span>
                          </li>
                          <li
                            className={`item-title ${
                              activeTab === "Review" ? "active" : ""
                            }`}
                            onClick={() => handleTabClick("Review")}
                          >
                            <span className="inner">Review</span>
                          </li>
                        </ul>
                        <div className="widget-content-tab">
                          {activeTab === "Description" && (
                            <div className="widget-content-inner active">
                              <div className="">
                                <p style={{ whiteSpace: "pre-wrap", wordBreak: "break-word", color: "#666" }}>
                                  {productData?.item_description}
                                </p>
                                {hasProductDescriptionContent() && (
                                  <h2 className="fs-18 fw-6 " style={{ marginBottom: "-20px" }}>Product Description</h2>
                                )}
                                {productData?.product_description && (
                                  <div >
                                    {productData.product_description.Ingredients && (
                                      <div >
                                        <h3 className="fs-16 fw-5 ">Ingredients</h3>
                                        <p style={{ whiteSpace: "pre-wrap", wordBreak: "break-word", color: "#666" }}>
                                          {productData.product_description.Ingredients}
                                        </p>
                                      </div>
                                    )}

                                    {productData.product_description["Allergen Info"] && (
                                      <div >
                                        <h3 className="fs-16 fw-5 ">Allergen Info</h3>
                                        <p style={{ whiteSpace: "pre-wrap", wordBreak: "break-word", color: "#666" }}>
                                          {productData.product_description["Allergen Info"]}
                                        </p>
                                      </div>
                                    )}

                                    {productData.product_description["Allergen Description"] && (
                                      <div >
                                        <h3 className="fs-16 fw-5 ">Allergen Description</h3>
                                        <p style={{ whiteSpace: "pre-wrap", wordBreak: "break-word", color: "#666" }}>
                                          {productData.product_description["Allergen Description"]}
                                        </p>
                                      </div>
                                    )}

                                    {productData.product_description["Nutritional Info"] && (
                                      <div>
                                        <h3 className="fs-16 fw-5 ">Nutritional Info</h3>
                                        <p style={{ whiteSpace: "pre-wrap", wordBreak: "break-word", color: "#666" }}>
                                          {productData.product_description["Nutritional Info"]}
                                        </p>
                                      </div>
                                    )}

                                    {/* {productData.product_description["Additional Info"] && (
                                      <div style={{ marginBottom: "20px" }}>
                                        <h3 className="fs-16 fw-5">Additional Info</h3>
                                        <p style={{ whiteSpace: "pre-wrap", wordBreak: "break-word", color: "#666" }}>
                                          {productData.product_description["Additional Info"]}
                                        </p>
                                      </div>
                                    )} */}
                                  </div>
                                )}

                                <div style={{ marginTop: "30px" }}>
                                  <h3 className="fs-16 fw-5 mb_12">Marketed By</h3>
                                  <p>
                                    Navya Bakeshop, Central Junction Angamaly
                                    Ernakulam, Kerala, India-683572, E-Mail :
                                    ang1@navyabakers.com, Phone : +91 9496001256
                                  </p>
                                </div>
                                <img
                                  src="/shopnow/images/fssai-logo.webp"
                                  width="100"
                                  alt=""
                                />
                                <br />
                                <p>
                                  <b>FSSAI Lic. No. xxxxxxxxxxx0168</b>
                                </p>
                              </div>
                            </div>
                          )}
                          {activeTab === "Review" && (
                            <div
                              className="widget-content-inner active"
                              style={{
                                fontFamily: "Albert Sans, sans-serif",
                              }}
                            >
                              <div className="row mb-3">
                                <div className="col-2 review-overview">
                                  <h2>{averageRating}</h2>
                                  <span>Based on {totalReviews} Ratings</span>
                                </div>
                                <div className="col-4">
                                  <div className="review-section">
                                    <div className="review-details">
                                      {[5, 4, 3, 2, 1].map((star, index) => (
                                        <div className="rating-bar" key={star}>
                                          <span>{star} ★</span>
                                          <div className="progress">
                                            <div
                                              style={{
                                                width: `${
                                                  ratingPercentages[star - 1]
                                                }%`,
                                              }}
                                            ></div>
                                          </div>
                                          <span className="percentage">
                                            {ratingPercentages[star - 1]}%
                                          </span>
                                        </div>
                                      ))}
                                    </div>
                                  </div>
                                </div>
                                <div className="col-6 text-end">
                                  {reviews?.filter(
                                    (item: any) => item.user === currentUserUuid
                                  ).length === 0 &&
                                    !addReview && (
                                      <div className="text-end">
                                        <button
                                          onClick={handleAddReview}
                                          id="addReviewBtn"
                                          className="tf-btn btn-fill animate-hover-btn radius-3 justify-content-center"
                                        >
                                          <span>Write a Review</span>
                                        </button>
                                      </div>
                                    )}
                                </div>
                              </div>

                              {addReview && (
                                <>
                                  <div id="reviewDiv">
                                    <div className="form-field">
                                      <label htmlFor="title">Title</label>
                                      <input
                                        type="text"
                                        id="title"
                                        placeholder="Enter review title"
                                        value={editedReview.review_heading}
                                        onChange={(e) =>
                                          setEditedReview({
                                            ...editedReview,
                                            review_heading: e.target.value,
                                          })
                                        }
                                      />
                                    </div>
                                    <div className="form-field">
                                      <label htmlFor="description">
                                        Description
                                      </label>
                                      <textarea
                                        id="description"
                                        rows={4}
                                        value={editedReview.review_text}
                                        onChange={(e) =>
                                          setEditedReview({
                                            ...editedReview,
                                            review_text: e.target.value,
                                          })
                                        }
                                        placeholder="Enter review description"
                                      ></textarea>
                                    </div>
                                    <label htmlFor="title">Rating</label>
                                    <div
                                      className="your-review"
                                      style={{ paddingBottom: "20px" }}
                                    >
                                      {Array.from({ length: 5 }).map(
                                        (_, index) => {
                                          const ratingValue = 5 - index; // Reverse order to keep the highest rating on the right
                                          return (
                                            <React.Fragment key={ratingValue}>
                                              <input
                                                type="radio"
                                                name="your-review"
                                                id={`rating-${ratingValue}`}
                                                checked={
                                                  editedReview.rating ===
                                                  ratingValue
                                                }
                                                onChange={() =>
                                                  setEditedReview({
                                                    ...editedReview,
                                                    rating: ratingValue,
                                                  })
                                                }
                                              />
                                              <label
                                                htmlFor={`rating-${ratingValue}`}
                                                style={{ cursor: "pointer" }}
                                              ></label>
                                            </React.Fragment>
                                          );
                                        }
                                      )}
                                    </div>
                                    <button
                                      onClick={handleSaveAdd}
                                      style={{ backgroundColor: "#000000" }}
                                      className="btn btn-success me-2"
                                    >
                                      Save Review
                                    </button>
                                    <button
                                      onClick={handleCancelAdd}
                                      className="btn btn-secondary"
                                    >
                                      Cancel
                                    </button>
                                  </div>
                                  {/* <div style={{ padding: "20px" }}>
                                <div className="rating mb-1">
                                  {Array.from({ length: 5 })?.map(
                                    (_, index) => {
                                      const ratingValue = index + 1;
                                      return (
                                        <i
                                          style={{ cursor: "pointer" }}
                                          key={ratingValue}
                                          className={`icon-start ${
                                            editedReview.rating >= ratingValue
                                              ? "filled"
                                              : ""
                                          }`}
                                          onClick={() =>
                                            setEditedReview({
                                              ...editedReview,
                                              rating: ratingValue,
                                            })
                                          }
                                        ></i>
                                      );
                                    }
                                  )}
                                </div>
                                <br />
                                <div className="mb-2">
                                  <input
                                    className="form-control"
                                    style={{
                                      direction: "ltr",
                                      fontSize: "16px",
                                    }}
                                    type="text"
                                    value={editedReview.review_heading}
                                    onChange={(e) =>
                                      setEditedReview({
                                        ...editedReview,
                                        review_heading: e.target.value,
                                      })
                                    }
                                    placeholder="Review Heading"
                                  />
                                </div>
                                <div className="mb-2">
                                  <textarea
                                    style={{ direction: "ltr" }}
                                    className="form-control"
                                    value={editedReview.review_text}
                                    onChange={(e) =>
                                      setEditedReview({
                                        ...editedReview,
                                        review_text: e.target.value,
                                      })
                                    }
                                    placeholder="Review Text"
                                  />
                                </div>

                                <button
                                  onClick={handleSaveAdd}
                                  className="btn btn-success me-2"
                                >
                                  Save Review
                                </button>
                                <button
                                  onClick={handleCancelAdd}
                                  className="btn btn-secondary"
                                >
                                  Cancel
                                </button>
                              </div> */}
                                </>
                              )}

                              {reviews?.map((review: any, index: any) => (
                                <div
                                  key={index}
                                  className="testimonial-item mb-3"
                                >
                                  {editingIndex === index ? (
                                    <>
                                      <div id="reviewDiv">
                                        <div className="form-field">
                                          <label htmlFor="title">Title</label>
                                          <input
                                            type="text"
                                            id="title"
                                            placeholder="Enter review title"
                                            value={editedReview.review_heading}
                                            onChange={(e) =>
                                              setEditedReview({
                                                ...editedReview,
                                                review_heading: e.target.value,
                                              })
                                            }
                                          />
                                        </div>
                                        <div className="form-field">
                                          <label htmlFor="description">
                                            Description
                                          </label>
                                          <textarea
                                            id="description"
                                            rows={4}
                                            value={editedReview.review_text}
                                            onChange={(e) =>
                                              setEditedReview({
                                                ...editedReview,
                                                review_text: e.target.value,
                                              })
                                            }
                                            placeholder="Enter review description"
                                          ></textarea>
                                        </div>
                                        <label htmlFor="title">Rating</label>
                                        <div
                                          className="your-review"
                                          style={{ paddingBottom: "20px" }}
                                        >
                                          {Array.from({ length: 5 }).map(
                                            (_, index) => {
                                              const ratingValue = 5 - index; // Reverse order to keep the highest rating on the right
                                              return (
                                                <React.Fragment
                                                  key={ratingValue}
                                                >
                                                  <input
                                                    type="radio"
                                                    name="your-review"
                                                    id={`rating-${ratingValue}`}
                                                    checked={
                                                      editedReview.rating ===
                                                      ratingValue
                                                    }
                                                    onChange={() =>
                                                      setEditedReview({
                                                        ...editedReview,
                                                        rating: ratingValue,
                                                      })
                                                    }
                                                  />
                                                  <label
                                                    htmlFor={`rating-${ratingValue}`}
                                                    style={{
                                                      cursor: "pointer",
                                                    }}
                                                  ></label>
                                                </React.Fragment>
                                              );
                                            }
                                          )}
                                        </div>
                                        <button
                                          onClick={handleSave}
                                          style={{ backgroundColor: "#000000" }}
                                          className="btn btn-success me-2"
                                        >
                                          Update Review
                                        </button>
                                        <button
                                          onClick={handleCancel}
                                          className="btn btn-secondary"
                                        >
                                          Cancel
                                        </button>
                                      </div>

                                      {/* <div style={{ padding: "20px" }}>
                                    <div className="rating mb-1">
                                      {Array.from({ length: 5 })?.map(
                                        (_, index) => {
                                          const ratingValue = index + 1;
                                          return (
                                            <i
                                              style={{ cursor: "pointer" }}
                                              key={ratingValue}
                                              className={`icon-start ${
                                                editedReview.rating >=
                                                ratingValue
                                                  ? "filled"
                                                  : ""
                                              }`}
                                              onClick={() =>
                                                setEditedReview({
                                                  ...editedReview,
                                                  rating: ratingValue,
                                                })
                                              }
                                            ></i>
                                          );
                                        }
                                      )}
                                    </div>
                                    <br />
                                    <div className="mb-2">
                                      <input
                                        className="form-control"
                                        style={{
                                          direction: "ltr",
                                          fontSize: "16px",
                                        }}
                                        type="text"
                                        value={editedReview.review_heading}
                                        onChange={(e) =>
                                          setEditedReview({
                                            ...editedReview,
                                            review_heading: e.target.value,
                                          })
                                        }
                                        placeholder="Review Heading"
                                      />
                                    </div>
                                    <div className="mb-2">
                                      <textarea
                                        style={{ direction: "ltr" }}
                                        className="form-control"
                                        value={editedReview.review_text}
                                        onChange={(e) =>
                                          setEditedReview({
                                            ...editedReview,
                                            review_text: e.target.value,
                                          })
                                        }
                                        placeholder="Review Text"
                                      />
                                    </div>

                                    <button
                                      onClick={handleSave}
                                      className="btn btn-success me-2"
                                    >
                                      Update Review
                                    </button>
                                    <button
                                      onClick={handleCancel}
                                      className="btn btn-secondary"
                                    >
                                      Cancel
                                    </button>
                                  </div> */}
                                    </>
                                  ) : (
                                    <>
                                      <div className="heading">
                                        {review.review_heading}
                                      </div>
                                      <div className="text">
                                        {review.review_text}
                                      </div>
                                      <div className="rating mb-1">
                                        {Array.from({ length: 5 })?.map(
                                          (_, i) => (
                                            <i
                                              key={i}
                                              className={`icon-start ${
                                                i < review.rating
                                                  ? "filled"
                                                  : ""
                                              }`}
                                            ></i>
                                          )
                                        )}
                                      </div>
                                      <div className="author">
                                        <div className="metas">
                                          {review.username &&
                                          review.username !== " None"
                                            ? review.username
                                            : "Anonymous User"}
                                        </div>
                                        <div className="metas">
                                          {moment(review.created_at).format(
                                            "DD MMM YYYY"
                                          )}
                                        </div>
                                      </div>
                                      {review.user === currentUserUuid && (
                                        <div className="author">
                                          <span
                                            onClick={() => handleEdit(index)}
                                            className="btn btn-warning me-2"
                                            style={{ color: "white" }}
                                          >
                                            <i className="fa-regular fa-pen-to-square"></i>{" "}
                                            Edit
                                          </span>
                                          <button
                                            onClick={() => handleDelete(index)}
                                            className="btn btn-danger"
                                          >
                                            <i className="fa-solid fa-trash"></i>{" "}
                                            Delete
                                          </button>
                                        </div>
                                      )}
                                      <br></br>
                                      <hr />
                                    </>
                                  )}
                                </div>
                              ))}
                              <ConfirmationDialog
                                title="Confirm Action"
                                open={dialogOpen}
                                onClose={closeDialog}
                                onConfirm={confirmAction}
                                content="Are you sure you want to delete this review?"
                              />
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </section>
            )}
          </>
        ) : (
          <>
            {" "}
            <section className="flat-spacing-4 pt_0 pb-5">
              <div
                className="tf-main-product section-image-zoom"
                key={productId}
                style={{ position: "relative", marginTop: "5rem" }}
              >
                <div
                  style={{
                    fontSize: "18px",
                    alignItems: "center",
                    display: "flex",
                    flexDirection: "column",
                  }}
                >
                  <span className="title wow fadeInUp" data-wow-delay="0s">
                    No data found
                  </span>
                </div>
              </div>
            </section>
          </>
        )}

        <PeopleAlsoBought />
        {/*<RecentlyViewed /> */}

        <Footer />
      </div>
      {/* )} */}
    </>
  );
};
