import CategorySection from "@/components/home/CategorySection";
import React, { ChangeEvent, useEffect, useRef, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/router";
import axios from "axios";
import Loader from "@/components/helpers/Loader";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/Redux/store";
import { setCategory } from "@/Redux/userSelectionSlice";
import { setVariations } from "@/Redux/productFiltersSlice";
import FavoritesIcon from "@/components/helpers/FavoritesIcon";
import { Toaster, toast } from "react-hot-toast";
import Cookies from "js-cookie";
import { fetchInitialCartData } from "@/Redux/cartAsyncActions";
import { Breadcrumb, Tooltip, message } from "antd";
import Link from "next/link";
import { motion } from "framer-motion";
import { Modal, Button, Input } from "antd";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import SimilarProducts from "@/components/similarproduct/SimilarProducts";
import Slider from "react-slick";

import MoreFromSeller from "@/components/ViewMorefromSeller/MoreFromSeller";
import { formatNumberWithCommas } from "@/components/commonFunctions/formatNumberWithCommas";
import { List } from "antd";
import { IoShareSocialOutline } from "react-icons/io5";
import { FaWhatsapp, FaRegCopy } from "react-icons/fa";
import { LiaTelegram } from "react-icons/lia";
// import { fetchDataWithCache } from "@/components/commonFunctions/dataCaching";
import { userActivity } from "@/components/commonFunctions/userActivity";
import Head from "next/head";

interface Category {
  id: string;
}

function SampleNextArrow(props: any) {
  const { className, style, onClick } = props;
  return (
    <div
      className={className}
      style={{
        ...style,
        borderRadius: "50%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        background: "#999",
        margin: "0 .5rem 0 0",
        zIndex: 20,
        padding: "20px",
      }}
      onClick={onClick}
    />
  );
}

function SamplePrevArrow(props: any) {
  const { className, style, onClick } = props;
  return (
    <div
      className={className}
      style={{
        ...style,
        borderRadius: "50%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        background: "#999",
        margin: "0 0 0 0.5rem",
        zIndex: 20,
        padding: "20px",
      }}
      onClick={onClick}
    />
  );
}

export default function BuyNow() {
  const router = useRouter();
  const { id } = router.query;
  const dispatch = useDispatch();
  const sliderRef = useRef<Slider>(null);

  var settings = {
    dots: false,
    infinite: true,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
    // initialSlide: 0,
    afterChange: (currentSlide: number) => {
      // console.log("Current slide index:", currentSlide);
      setSelectedGalleryIndex(currentSlide);
    },
    nextArrow: <SampleNextArrow />,
    prevArrow: <SamplePrevArrow />,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 3,
          infinite: true,
          dots: true,
        },
      },
      {
        breakpoint: 1000,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1,
          // initialSlide: 2,
        },
      },
      {
        breakpoint: 480,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1,
        },
      },
    ],
  };

  const cartItems = useSelector((state: RootState) => state.cart.items);

  const [productDetail, setProductDetail] = React.useState<any>(null);
  const [categoryData, setCategoryData] = React.useState<any[]>([]);

  const [categoryName, setcategoryName] = React.useState<string>("");

  const [subcategoryName, setsubcategoryName] = React.useState<string>("");

  // const [isDelivery, setIsDelivery] = React.useState<boolean>(false);

  const [featuredImage, setFeaturedImage] = React.useState("");

  const [selectedGalleryIndex, setSelectedGalleryIndex] = React.useState(0);

  const [loading, setLoading] = React.useState<boolean>(false);

  const [quantity, setQuantity] = React.useState<string>("1");

  const [variationIds, setVariationIds] = useState<string[]>([]);

  const [description, setDescription] = useState<string[]>([]);

  const [alreadyInBag, setAlreadyInBag] = useState<string>("ADD TO BAG");

  const _loggedIn_user = useSelector((state: RootState) => state.user.user);

  const [productNature, setproductNature] = useState({
    categoryId: "",
    subcategoryId: "",
  });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [counterPrice, setCounterPrice] = useState("");

  const [isShareModalVisible, setIsShareModalVisible] = useState(false);

  const [pageloading, setPageLoading] = useState<boolean>(true);

  const showModal = () => {
    setIsShareModalVisible(true);
  };

  const handleCancel = () => {
    setIsShareModalVisible(false);
  };

  const shareOptions = [
    {
      name: "WhatsApp",
      action: () =>
        window.open(
          `https://api.whatsapp.com/send?text=${encodeURIComponent(
            `${window.location.origin}${router.asPath}`,
          )}`,
        ),
      icon: <FaWhatsapp className="text-xl m-1" />,
    },
    {
      name: "Telegram",
      action: () =>
        window.open(
          `https://t.me/share/url?url=${encodeURIComponent(
            `${window.location.origin}${router.asPath}`,
          )}`,
        ),
      icon: <LiaTelegram className="text-xl m-1" />,
    },
    {
      name: "Copy Link",
      action: () => {
        navigator.clipboard.writeText(
          `${window.location.origin}${router.asPath}`,
        );
        setIsShareModalVisible(false);
        message.success("Copied.");
      },
      icon: <FaRegCopy className="text-xl m-1" />,
    },
  ];

  const authToken = Cookies.get("jazz_token");

  // Configure the Axios instance with the authorization header
  const axiosInstance = axios.create({
    baseURL: "https://api.jazzagain.com/public/index.php",
    headers: {
      authorization: `Bearer ${authToken}`,
    },
  });

  const [showHighPriceModal, setShowHighPriceModal] = useState(false);

  const handleNegotiableClick = async (price: string) => {
    const numericPrice = parseFloat(price);

    if (!productDetail || !_loggedIn_user) {
      toast.error("Product or user info missing");
      return;
    }

    if (isNaN(numericPrice)) {
      toast.error("Please enter a valid number.");
      return;
    }

    if (numericPrice < 1000) {
      toast.error("Price must be at least ₦1,000.");
      return;
    }

    if (numericPrice > 50000) {
      setShowHighPriceModal(true); // Show custom modal
      return;
    }
    const payload = {
      title: "Jazzagain - Counter Offer",
      body: `A buyer has given counter offer for ${productDetail.productTitle} at ₦${numericPrice}. If interested, update your product price.`,
      data: {
        type: "Counter Offer",
        productId: productDetail.id,
        counterPrice: numericPrice.toString(),
        clickUrl: `https://api.jazzagain.com/product/edit/${productDetail.id}`, // ✅ important!
      },
      userId: productDetail.userId, // Seller ID
      sender: _loggedIn_user.id, // Buyer ID
    };

    try {
      await axiosInstance.post(
        "https://api.jazzagain.com/node/notification-token/v2/send-notification",
        payload,
      );
      toast.success("Counter offer sent successfully!");
      setIsModalVisible(false);
      setCounterPrice("");
    } catch (error) {
      console.error("Error sending counter offer notification:", error);
      toast.error("Failed to send counter offer.");
    }
  };

  async function fetchDataWithCache(endpoint: string) {
    const cacheKey = `cache_${endpoint}`;
    const cached = localStorage.getItem(cacheKey);

    // const authToken = Cookies.get("jazz_token");

    // const axiosInstance = axios.create({
    //   baseURL: "https://api.jazzagain.com/public/index.php",
    // });

    if (cached) {
      const { data, timestamp } = JSON.parse(cached);
      const isFresh = Date.now() - timestamp < 120000;

      if (isFresh) {
        return data;
      }
    }

    // If data is not in cache or is stale, fetch from API
    try {
      const response = await axiosInstance.get(endpoint);
  const data = response.data;


      // Cache the new data along with the current timestamp
      localStorage.setItem(
        cacheKey,
        JSON.stringify({ data, timestamp: Date.now() }),
      );
      return data;
    } catch (error) {
      throw error;
    }
  }

useEffect(() => {
if (!router.isReady || !id || loading) return; // Loading state check karein
  const productId = Array.isArray(id) ? id[0] : id;

  if (!productId || productId === "undefined") return;

  setLoading(true);

  const getSingleProductData = async () => {
    try {
      const response = await fetchDataWithCache(
        `/api/getSingleProduct/${productId}`
      );

const product = response.product;
      setProductDetail(product);

      setDescription(product.productDescription?.split("\n") || []);

      const catId = product.categoryId;
      const subcatId = product.subCategoryId;

      setproductNature({ categoryId: catId, subcategoryId: subcatId });

      const allCategories = await fetchDataWithCache(`/api/getCategories`);

setCategoryData(allCategories.categories);
  const cat = allCategories?.categories?.find(
  (i: Category) => i.id === catId
);

      setcategoryName(cat?.categoryName || "");

      subCategoryName(product);

      const foundProduct = cartItems.find(
        (p: any) => p.productId === product.id
      );

      if (foundProduct) setAlreadyInBag("ALREADY IN BAG");

    } catch (error) {
      console.error("Error:", error);
    } finally {
      setLoading(false);
      setPageLoading(false);
    }
  };

  getSingleProductData();
}, [router.isReady, router.query.id]);
  React.useEffect(() => {
    userActivity(
      _loggedIn_user?.id,
      "website",
      "singleProductPage",
      {
        pageVisit: `/`,
      },
      navigator.userAgent,
    );
    if (productDetail?.productFeaturedImage) {
      setFeaturedImage(productDetail.productFeaturedImage);
    }
  }, [productDetail]);

  const handleGalleryImageClick = (imageUrl: string, index: number) => {
    // setFeaturedImage(imageUrl);
    // console.log(imageUrl, index)
    setSelectedGalleryIndex(index);
    sliderRef.current?.slickGoTo(index);
  };

const Add_to_Cart = async () => {
  const pid = productDetail?.id || productDetail?.id || router.query.id;

  if (!authToken) {
    localStorage.setItem("selectedCartProduct", JSON.stringify(productDetail));
    return router.push("/auth/login");
  }

  if (!pid || pid === "undefined") {
    return toast.error("Product loading... please wait");
  }

  const autoSelectVariations: string[] = [];
  productDetail?.variations?.forEach((i: any) => {
    if (i?.variation?.length > 0 && i.variation[0]?.id) {
      autoSelectVariations.push(i.variation[0].id);
    }
  });

  // Backend Error ke mutabiq keys ko CamelCase mein rakha hai
  const formData = new FormData();
  formData.append("productId", pid); // Backend Error: "productId field is required"
  formData.append("amount", (productDetail?.productSellingPrice || 0).toString());
  formData.append("quantity", quantity.toString());
  formData.append("totalAmount", (Number(productDetail?.productSellingPrice || 0) * Number(quantity)).toString()); // Backend Error: "totalAmount field is required"
  
  // Variations ko array format mein bhej rahe hain
  if (autoSelectVariations.length > 0) {
    formData.append("variationId", JSON.stringify(autoSelectVariations));
  } else {
    formData.append("variationId", "[]");
  }

  try {
    localStorage.removeItem("cache_/api/user/carts");

    const response = await axios({
      method: "post",
      url: "https://api.jazzagain.com/public/index.php/api/user/carts",
      data: formData,
      headers: {
        "Authorization": `Bearer ${authToken}`,
        "Content-Type": "multipart/form-data",
      },
    });

    if (response.status === 200 || response.status === 201) {
      toast.success("Added to Bag!");
      dispatch(fetchInitialCartData());
      router.push("/productDetail");
    }
  } catch (err: any) {
    console.log("Sent Data Check:", Object.fromEntries(formData));
    console.error("Backend Error Detail:", err.response?.data);
    
    const serverMessage = err.response?.data?.message || "Failed to add to cart";
    toast.error(serverMessage);
  }
};

  const buy_Now = (item: any) => {
    userActivity(
      _loggedIn_user?.id,
      "website",
      "Buy now ",
      {
        pageVisit: `/buynow/${productDetail.id}`,
      },
      navigator.userAgent,
    );
  const productId = item?.id || item?.id;
 if (!productId) {
    toast.error("Product not ready!");
    return;
  }
    if (!authToken) {
      localStorage.setItem("selectedProduct", JSON.stringify(item));
      return router.push("/auth/login");
    }
    if (_loggedIn_user?.id == productDetail.userId) {
      return toast.error("You cant buy your own product !");
    }
    if (item.productAvailability === 0) {
      return toast.error("Product Sold out !");
    }
    // console.log(item);
    dispatch(setVariations(variationIds));
    // router.push(`/confirmAddress?buy=${item.id}&q=${quantity}`);
  router.push(`/buynow/${productId}`);
  };

  const GotoFilterSection = (name: string, id: string) => {
    dispatch(
      setCategory({
        category: name,
        categoryID: id,
      }),
    );
    router.push("/product");
    // console.log(name, id);
  };

const subCategoryName = async (item: any) => {
  try {
    const res = await axios.get(
      `https://api.jazzagain.com/public/index.php/api/getSubCategories/${item?.categoryId}`
    );

    const found = res?.data?.subCategories?.find(
      (i: any) => i.id === item?.subCategoryId
    );

    // ✅ Safe handling
    setsubcategoryName(found?.subCategoryName || "Subcategory not found");

    return found?.subCategoryName || "Subcategory not found";

  } catch (error) {
    console.error("Error fetching subcategories", error);
    setsubcategoryName("Error fetching subcategory");
    return "Error fetching subcategory";
  }
};

  if (pageloading) {
    return <Loader />;
  }

  return !productDetail ? (
    <div className="flex items-center justify-center h-screen bg-gray-100">
      <div className="bg-white p-8 rounded shadow-md text-center">
        <h1 className="text-4xl font-bold mb-4">404 - Not Found</h1>
        <p className="text-gray-600 mb-8">
          The product page you are looking for does not exist.
        </p>
        <Link href="/">
          <p className="text-blue-500 hover:underline">Go to Homepage</p>
        </Link>
      </div>
    </div>
  ) : (
    <>
      <Head>
        <link rel="shortcut icon" href="/images/jazzagian-logo.png" />
        <script
          dangerouslySetInnerHTML={{
            __html: `
              !function(f,b,e,v,n,t,s)
              {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
              n.callMethod.apply(n,arguments):n.queue.push(arguments)};
              if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
              n.queue=[];t=b.createElement(e);t.async=!0;
              t.src=v;s=b.getElementsByTagName(e)[0];
              s.parentNode.insertBefore(t,s)}(window, document,'script',
              'https://connect.facebook.net/en_US/fbevents.js');
              fbq('init', '360254480441103');
              fbq('track', 'singleproduct');
            `,
          }}
        />
        <noscript>
          <Image
            height="1"
            width="1"
            alt="facebook link"
            style={{ display: "none" }}
            src="https://www.facebook.com/tr?id=360254480441103&ev=singleproduct&noscript=1"
          />
        </noscript>
      </Head>

      <div>
        <CategorySection />
        <Toaster
          toastOptions={{
            className: "",
            duration: 5000,
          }}
        />

        <hr className="border border-gray-300 w-[90%] mx-auto my-3 sm:my-6" />
        <div>
          <Breadcrumb
            className="w-[90%] mx-auto my-1 text-[18px] cursor-pointer"
            items={[
              {
                title: <Link href="/">Home</Link>,
              },
              {
                title: `${categoryName}`,
                onClick: () =>
                  GotoFilterSection(categoryName, productDetail.categoryId),
              },
              {
                title: `${subcategoryName}`,
              },
            ]}
          />
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 mx-auto ">
          <div className="my-2">
            <div className="p-[1rem] overflow-hidden flex  justify-center ">
              <div className="flex flex-col rounded-lg gap-1">
                {productDetail?.galleries.map((item: any, index: number) => {
                  const imageUrl = `https://api.jazzagain.com/public/${item.imageUrl}`;
                  // Check if the image URL is valid
                  if (!item.imageUrl || item.imageUrl.trim() === "") {
                    return null; // Skip rendering if the URL is invalid
                  }

                  return (
                    <div
                      key={index}
                      className={`cursor-pointer flex rounded ${
                        selectedGalleryIndex === index
                          ? "border border-[#FF332B]"
                          : ""
                      }`}
                    >
                      <Image
                        src={imageUrl}
                        width={100}
                        height={100}
                        alt={`${item?.imageUrl}`}
                        className="object-cover w-20 h-24"
                        // style={{ maxHeight: "60px", maxWidth: "80px" }}
                        onClick={() =>
                          handleGalleryImageClick(item.imageUrl, index)
                        }
                        onError={(e) => {
                          // console.log("ImageError");
                          const imageElement = e.target as HTMLImageElement;
                          if (imageElement.parentElement) {
                            imageElement.parentElement.style.display = "none";
                          }
                        }}
                      />
                    </div>
                  );
                })}
              </div>
              <div className="w-[50%] ml-10 sm:ml-16">
                <Slider {...settings} ref={sliderRef}>
                  {productDetail?.galleries.map((item: any, index: number) => {
                    if (
                      !item ||
                      typeof item.imageUrl !== "string" ||
                      item.imageUrl.trim() === ""
                    ) {
                      return null; // Skip rendering if item or imageUrl is invalid
                    }

                    const imageUrl = `https://api.jazzagain.com/public/${item.imageUrl}`;

                    return (
                      <div
                        key={index}
                        style={{
                          display: "flex",
                        }}
                      >
                        <div className="relative">
                          <Image
                            src={imageUrl}
                            width={500}
                            height={500}
                            alt={`${item?.imageUrl}`}
                            onError={(
                              e: React.SyntheticEvent<HTMLImageElement, Event>,
                            ) => {
                              // console.log("ImageError");
                              // Move to the next image when an error occurs
                              // e.currentTarget.remove();
                              e.currentTarget.src = `https://api.jazzagain.com/public/${featuredImage}`;

                              setSelectedGalleryIndex(
                                (prevIndex) =>
                                  (prevIndex + 1) %
                                  productDetail?.galleries.length,
                              );
                              sliderRef.current?.slickGoTo(0);
                            }}
                          />
                          <div className="absolute bottom-0 right-0">
                            {(productDetail?.negotiable === true ||
                              productDetail?.negotiable === "true") && (
                              <div className="flex justify-end ">
                                <span className="bg-[#FE342B] text-white text-[10px] px-2 py-[2px] rounded-t-md">
                                  Price Negotiable
                                </span>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </Slider>
              </div>
            </div>
          </div>
          <div className=" p-[1rem]">
            <h2 className="text-[#FF332B] text-2xl py-2 font-semibold">
              {productDetail?.productTitle}
<Tooltip title="share">
  <span>
    <IoShareSocialOutline
      onClick={showModal}
      className="cursor-pointer inline text-2xl ml-10"
    />
  </span>
</Tooltip>
            </h2>
            <p className="text-sm w-full text-justify">
              {/* {productDetail?.productAge} year old <br /> */}
              {productDetail?.productShortDescription}
            </p>
            <div className="flex items-center mt-3">
              <div className="pr-2 py-1 inline-block text-lg">
                <div className="flex items-center">
                  <span className="sm:pr-6 py-1 sm:py-2 text-3xl font-semibold">
                    <span className="mr-3"> &#8358;</span>
                    {formatNumberWithCommas(productDetail?.productSellingPrice)}
                    {/* <Button type="primary" icon={<ShareAltOutlined />} onClick={showModal}>
                    Share
                  </Button> */}
                   <Modal
  title="Send Counter Offer"
  open={isModalVisible}
  onCancel={() => setIsModalVisible(false)}
                      centered={true}
                      width={300}
                      footer={null}
                    >
                      <List
                        className="cursor-pointer"
                        dataSource={shareOptions}
                        renderItem={(item) => (
                          <List.Item onClick={item.action}>
                            {item.icon}
                            <List.Item.Meta
                              title={item.name}
                              className="ml-3"
                            />
                          </List.Item>
                        )}
                      />
                    </Modal>
                  </span>
                  <span className="text-lg text-[#FE342B]">
                    -{productDetail?.productDiscountPercentage} %{" "}
                  </span>
                </div>
                <p className="font-medium">
                  <span> Original Price: &#8358;</span>
                  <span className="line-through">
                    {formatNumberWithCommas(
                      productDetail?.productOriginalPrice,
                    )}
                  </span>
                </p>
              </div>
              <div className="ml-4">
                <FavoritesIcon itemId={productDetail?.id} />
              </div>
            </div>
            {/* <div className="text-xs py-1">
            <span className="text-[#FF332B]">Hurry!</span> Likely to be sold out
            in 3 days
          </div> */}
            {/* <p className="">
            {productDetail?.productType === "variable" &&
              productDetail?.variations.length >= 1
              ? "Size"
              : null}
          </p> */}
            <div className="flex m-2">
              {productDetail?.productType === "variable" &&
              productDetail?.variations.length >= 1 ? (
                <>
                  {productDetail.variations?.map((i: any) => {
if (i?.attribute?.[0]?.attributeName?.toLowerCase() === "size") {                      return (
                        <>
                          <p className="mr-10">
                            {i.attribute[0]?.attributeName}
                          </p>
                          <span
                            className={`bg-gray-200 mb-2 min-w-min text-sm text-center rounded-lg shadow-md mr-4 p-2 cursor-pointer hover:bg-gray-300`}
                            // onClick={() => storingVariations(i.variation[0]?.id)}
                          >
                            {i.variation[0]?.variationName}
                          </span>
                        </>
                      );
                    } else {
                      return null;
                    }
                  })}
                </>
              ) : null}
            </div>
            {/* <p className="">
            {productDetail?.productType === "variable" &&
              productDetail?.variations.length >= 1
              ? "Color"
              : null}
          </p> */}
            <div className="flex m-2">
              {productDetail?.productType === "variable" &&
              productDetail?.variations.length >= 1 ? (
                <>
                  {productDetail.variations?.map((i: any) => {
                  if (i?.attribute?.[0]?.attributeName?.toLowerCase() === "color") {
                      return (
                        <>
                          <p className="mr-7">
                            {i.attribute[0]?.attributeName}
                          </p>
                          <span
                            className={`bg-gray-200 text-center text-sm rounded-lg shadow-md mr-4 p-2 cursor-pointer hover:bg-gray-300 ${
                              variationIds.includes(i.variation[0]?.id)
                                ? "border-2 border-[#FF332B]"
                                : ""
                            }`}
                          >
                            {i.variation[0]?.variationName}
                          </span>
                        </>
                      );
                    } else {
                      return null;
                    }
                  })}
                </>
              ) : null}
            </div>
            <div className="my-[1rem]">
              <motion.button
                className="bg-[#FF332B] rounded  sm:text-base px-3 text-white p-2 mr-3"
                onClick={() => Add_to_Cart()}
                whileHover={{ scale: 1.1 }}
                transition={{ duration: 0.3 }}
                disabled={alreadyInBag === "ALREADY IN BAG"}
                style={{
                  cursor:
                    alreadyInBag === "ALREADY IN BAG"
                      ? "not-allowed"
                      : "pointer",
                }}
              >
                {alreadyInBag}
              </motion.button>
              <motion.button
                className="bg-gray-700 rounded sm:text-base px-3 text-white p-2 mr-2"
                onClick={() => buy_Now(productDetail)}
                whileHover={{ scale: 1.1 }}
                transition={{ duration: 0.3 }}
              >
                BUY NOW
              </motion.button>
              {(productDetail?.negotiable === true ||
                productDetail?.negotiable === "true") && (
                <motion.button
                  className="bg-gray-700 rounded sm:text-base px-3 text-white p-2"
                  onClick={() => setIsModalVisible(true)}
                  whileHover={{ scale: 1.1 }}
                  transition={{ duration: 0.3 }}
                >
                  Counter Offer
                </motion.button>
              )}

              <Modal
                title="Send Counter Offer"
                open={isModalVisible}
                onCancel={() => setIsModalVisible(false)}
                footer={null}
              >
                <Input
                  type="number"
                  value={counterPrice}
                  onChange={(e) => {
                    const value = e.target.value;
                    if (value.length <= 5) {
                      setCounterPrice(value);
                    }
                  }}
                  placeholder="Enter your offer price"
                  prefix="₦"
                />

                <motion.button
                  className="bg-gray-700 rounded sm:text-base px-3 text-white p-2 mt-4"
                  onClick={() => handleNegotiableClick(counterPrice)}
                  whileHover={{ scale: 1.1 }}
                  transition={{ duration: 0.3 }}
                >
                  Send
                </motion.button>
              </Modal>

              <div className="w-full mx-auto my-3">
                <h3 className="text-[#FF332B]">Product Description</h3>
                {description.map((line, index) => (
                  <p key={index} className="text-justify text-sm">
                    {line}
                  </p>
                ))}
              </div>
            </div>
          </div>
          {/* <div className="w-full px-[1rem] mx-auto">
        <h3 className="text-[#FF332B]">Product Details</h3>
        {description.map((line, index) => (
          <p key={index} className="text-justify text-sm">
            {line}
          </p>
        ))}
      </div> */}
          <div></div>
        </div>

        <div className="w-[85%] mx-auto">
          <div className="w-full px-[1rem] sm:px-[1rem] mx-auto">
            <SimilarProducts nature={productNature} />
          </div>

          <hr className="border border-gray-300 w-[90%] mx-auto my-3 sm:my-6" />

          <div className="w-full px-[1rem] sm:px-[1rem] mx-auto">
            <div className="flex justify-between mt-[2rem]">
              <h2 className="text-[#FF332B] text-base">More from the Seller</h2>
            </div>
            <MoreFromSeller sellerId={productDetail?.userId} />
          </div>
        </div>
      </div>
    </>
  );
}
