"use client";

import React, { useEffect, useState, useRef } from "react";
import BidCard from "../../../../components/bayerProfile/pages/components/BidCard";
import { RootState } from "../../../../store";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { useParams, useRouter } from "next/navigation";
import { formatDate } from "../../../../common/DateFormant";
import AuctionTimer from "../../../../components/bayerProfile/pages/components/AuctionTimer";
import { FaInfoCircle } from "react-icons/fa";

import {
  ongoingBids,
  viewListing,
  viewSaller,
  createBid,
  Wishlist,
  DeleteWishlist,
  viewPrice,
  placeOrder,
  getsIncrement,
  tracklistings,
} from "../../../../api/api";
import Popup from "../../../../common/ConfirmationPopUp";
import { toast } from "react-toastify";
import Swal from "sweetalert2";
import cents from "../../../../assets/cent.png";
import ImageModal from "../../../../components/bayerProfile/pages/components/ImageModal";
import Link from "next/link";
import { resetBidStatus } from "../../../../slice/bidSlice";
import AuctionProduct from "../../../../common/AuctionProduct";
import { reset } from "../../../../slice/ViewListingSlice";
import PriorityBids from "../../../../components/bayerProfile/pages/components/PriorityBids";
import ListingBids from "../../../../components/bayerProfile/pages/components/ListingBids";
import { convertCurrency } from "../../../../utils/convertCurrency";
import Image from "next/image";
import ClientShareButtons from "../../../../components/ClientShareButtons";
import Pusher from "pusher-js";
import AuctionResultPopup from "../../../../common/AuctionResultPopup";
import { DateTime } from "luxon";
import safeParseTime from "../../../../utils/dateUtils";

const AuctionInfo: React.FC = () => {
  const [amount, setAmount] = useState<any>();
  const [bidSubmitted, setBidSubmitted] = useState(false);
  const dispatch = useDispatch<any>();
  const pusherRef = useRef<Pusher | null>(null);
  const router = useRouter();
  const params = useParams();
  const id = params?.id as string;
  const productName = params?.productName as string;
  const productCategoryName = params?.categoryName as string;
  const [showPopup, setShowPopup] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [selectedProduct, setSelectedProduct] = useState<any>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [orderData, setOrderData] = useState("");
  const { data: listingData, loading } = useSelector(
    (state: RootState) => state.viewListingReducer
  );
  const trackListData = useSelector(
    (state: RootState) => state.AllListingReducer
  );
  console.log("track list", trackListData);

  const { incrementData } = useSelector(
    (state: RootState) => state.MessageCountReducer
  );
  const AuctionSellerFee = incrementData?.data?.auctionFee[0]?.seller_fee;
  const { cashWalletHistoryData } = useSelector(
    (state: RootState) => state.WalletReducer
  );
  const WalletBalance = cashWalletHistoryData?.wallet_balance;
  const { userData, isLoggedIn } = useSelector(
    (state: RootState) => state.loginReducer
  );
  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const settings = homedata?.data?.settings;
  const userTimeZone = settings?.default_timezone || "UTC";

  const increments = incrementData?.data?.increments || [];
  const { status, error } = useSelector((state: RootState) => state.BidReducer);
  const { ongoingData } = useSelector(
    (state: RootState) => state.OnGoingBidsReducer
  );
  const userID = listingData?.data?.listing?.user_id;
  const CurrentUserID = userData?.data?.user.id;
  const viewListingData = listingData?.data?.listing;
  const [showConfirmBuyPopup, setShowConfirmBuyPopup] = useState(false);
  const [isListingBidsOpen, setIsListingBidsOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isOrderPlaced, setIsOrderPlaced] = useState(false);
  const [wasCancelled, setWasCancelled] = useState(false);
  const [selectedImage, setSelectedImage] = useState(
    viewListingData?.images?.[0]
  );
  const [isModalOpens, setIsModalOpens] = useState(false);
  const [auctionEnded, setAuctionEnded] = useState(false);
  const [isPriceUnlocked, setIsPriceUnlocked] = useState(false);

  const domainUrl = process.env.NEXT_PUBLIC_PRODUCT_URL!;
  const rates = useSelector(
    (state: RootState) => state.CurrencyExchangeRateReducer.rates
  );
  const currency = useSelector(
    (state: any) => state.CurrencyReducer.selectedCurrency
  );
  const closeModal = () => {
    setIsModalOpens(false); // Close modal
  };

  useEffect(() => {
    const routesToPrefetch = [
      "/profile/chat",
      "/profile/wallet/transaction/",
      "/profile/listing",
      "/",
    ];

    routesToPrefetch.forEach((route) => {
      router.prefetch(route);
    });
  }, [router]);

  const handleImageClick = (image: string) => {
    setSelectedImage(image);
    setIsModalOpens(true);
  };

  const getIncrement = (amount: number, increments: any[]) => {
    for (const range of increments) {
      const min = parseFloat(range.min_price);
      const max = range.max_price ? parseFloat(range.max_price) : Infinity;

      if (amount >= min && amount <= max) {
        return parseFloat(range.increment);
      }
    }
    return 0; // Default fallback if not matched
  };

  const productUrl = `${domainUrl}/auction/${id}/${productCategoryName}/${productName}`;
  const metaTitle = viewListingData?.product_name || "Auction Item";
  const metaDescription =
    viewListingData?.description?.substring(0, 160) ||
    "Check out this amazing auction item!";

  const [likedProducts, setLikedProducts] = useState<{
    [key: string]: boolean;
  }>({});

  const toggleLike = async (productId: string) => {
    if (!CurrentUserID) {
      const formattedCategoryName = viewListingData?.category?.name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();
      const productName = viewListingData?.product_name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();

      const returnUrl = `/auction/${id}/${formattedCategoryName}/${productName}`;
      router.push(`/auth/login?callbackUrl=${encodeURIComponent(returnUrl)}`);
      return;
    }
    const isCurrentlyLiked = listingData?.data?.wishlist;
    // Optimistically update the local state to reflect the change
    setLikedProducts((prevLikedProducts) => ({
      ...prevLikedProducts,
      [productId]: !isCurrentlyLiked,
    }));

    try {
      if (!isCurrentlyLiked) {
        await dispatch(Wishlist(productId)).unwrap();
        dispatch(viewListing({ id: id, user_id: CurrentUserID }));
        toast.success("Added to wishlist!");
      } else {
        await dispatch(DeleteWishlist(productId)).unwrap();
        dispatch(viewListing({ id: id, user_id: CurrentUserID }));
        toast.success("Removed from wishlist!");
      }
    } catch (error) {
      console.log(error);
      // Revert the local state if the API call fails
      setLikedProducts((prevLikedProducts) => ({
        ...prevLikedProducts,
        [productId]: isCurrentlyLiked,
      }));

      // Show an error message
      toast.error(
        `Error ${!isCurrentlyLiked ? "adding to" : "removing from"} wishlist.`
      );
    }
  };

  const productId = listingData?.data?.listing?.id;
  const isProductLiked =
    listingData?.data?.wishlist || likedProducts[productId] || false;

  const handleCarfax = async () => {
    const vin = viewListingData.vin_number.trim();
    await navigator.clipboard.writeText(vin);
    try {
      const country = viewListingData?.location;
      if (country === "Canada") {
        window.open(
          `https://www.carfax.ca/tools/vin-decode/vin-decode-results?vin=${vin}`,
          "_blank"
        );
      } else {
        await navigator.clipboard.writeText(vin);
        window.open(
          "https://www.carfax.com/vehicle-history-reports/",
          "_blank"
        );
      }
    } catch (error) {
      console.log(error);

      alert("Could not determine your location. Opening default Carfax.");
      window.open(
        `https://www.carfax.ca/tools/vin-decode/vin-decode-results?vin=${vin}`,
        "_blank"
      );
    }
  };
  //
  useEffect(() => {
    if (id) {
      dispatch(viewListing({ id: id, user_id: CurrentUserID })).catch(() => {
        toast.error("Failed to load listing details.");
      });
    }
  }, [dispatch, id, CurrentUserID, auctionEnded]);

  useEffect(() => {
    return () => {
      dispatch(resetBidStatus());
    };
  }, [dispatch]);
  useEffect(() => {
    return () => {
      dispatch(tracklistings(id));
    };
  }, [id, dispatch]);

  useEffect(() => {
    return () => {
      dispatch(reset());
    };
  }, [dispatch]);

  // Fix the useEffect call

  useEffect(() => {
    dispatch(getsIncrement());
  }, [dispatch]);

  useEffect(() => {
    dispatch(ongoingBids(id));
  }, [dispatch, id]);

  useEffect(() => {
    if (userID && CurrentUserID) {
      dispatch(viewSaller({ seller_id: userID, user_id: CurrentUserID }));
    }
  }, [userID, CurrentUserID, dispatch]);

  useEffect(() => {
    if (status === "succeeded" && bidSubmitted) {
      toast.success("Bid submitted successfully!");
      dispatch(viewListing({ id: id, user_id: CurrentUserID }));
      setBidSubmitted(false);
      dispatch(resetBidStatus());
    } else if (status === "failed") {
      toast.error(error || "An error occurred while submitting the bid.");
      setBidSubmitted(false);
      dispatch(viewListing({ id: id, user_id: CurrentUserID }));
      dispatch(resetBidStatus());
    }
  }, [status, error, bidSubmitted, dispatch, id, CurrentUserID]);

  useEffect(() => {
    setSelectedImage(viewListingData?.images[0]);
  }, [viewListingData]);

  useEffect(() => {
    if (!wasCancelled && viewListingData?.max_bid_required) {
      setAmount(viewListingData.max_bid_required);
    }

    // Reset wasCancelled after effect
    if (wasCancelled) {
      setWasCancelled(false);
    }
  }, [wasCancelled, viewListingData]);

  const handleSubmit = (e: any) => {
    e.preventDefault();

    if (!CurrentUserID) {
      const formattedCategoryName = viewListingData?.category?.name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();
      const productName = viewListingData?.product_name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();

      const returnUrl = `/auction/${id}/${formattedCategoryName}/${productName}`;
      router.push(`/auth/login?callbackUrl=${encodeURIComponent(returnUrl)}`);
      return; // ✅ stop further code
    }

    if (amount === undefined) return;
    setIsModalOpen(true);
  };

  // When the user confirms in the modal, proceed with dispatching the bid
  const handleConfirm = async () => {
    setIsModalOpen(false);
    try {
      const result = await dispatch(
        createBid({ listing_id: id, amount })
      ).unwrap();
      console.log("Result check:", result);
      setBidSubmitted(true);
      dispatch(ongoingBids(id));
    } catch {
      return null;
    }
  };

  // Format the amount using the Indian numbering format
  const formattedAmount = amount ? amount.toLocaleString("en-IN") : "";

  const handleChange = (e: any) => {
    const rawValue = e.target.value.replace(/,/g, "");
    if (rawValue === "") {
      setAmount(undefined);
    } else {
      const numberValue = Number(rawValue);
      if (!isNaN(numberValue)) {
        setAmount(numberValue);
      } else {
        setAmount(undefined);
      }
    }
  };

  const handleUnlockPrice = async (amount: number, listingId: number) => {
    if (!CurrentUserID) {
      const formattedCategoryName = viewListingData?.category?.name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();
      const productName = viewListingData?.product_name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();

      const returnUrl = `/auction/${id}/${formattedCategoryName}/${productName}`;
      router.push(`/auth/login?callbackUrl=${encodeURIComponent(returnUrl)}`);
      return;
    }

    try {
      const result = await dispatch(
        viewPrice({ amount, listing_id: listingId })
      );
      if (viewPrice.fulfilled.match(result)) {
        setShowPopup(false);
        toast.success("Reserve item unlocked successfully");
        await dispatch(viewListing({ id: id, user_id: CurrentUserID }));
        setTimeout(() => {
          setShowConfirmBuyPopup(true);
        }, 500);
      } else if (viewPrice.rejected.match(result)) {
        const error = String(
          result.payload || "Failed to unlock price. Please try again."
        );
        setErrorMessage(error);
      }
    } catch {
      setErrorMessage("An unexpected error occurred. Please try again.");
    }
  };

  const handleUnlockPriceWithConfirmation = async (
    amount: number,
    listingId: number
  ) => {
    if (!CurrentUserID) {
      const formattedCategoryName = viewListingData?.category?.name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();
      const productName = viewListingData?.product_name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();

      const returnUrl = `/auction/${id}/${formattedCategoryName}/${productName}`;
      router.push(`/auth/login?callbackUrl=${encodeURIComponent(returnUrl)}`);
      return;
    }

    const result = await Swal.fire({
      title: "Unlock Price",
      text: "Are you sure you want to unlock the price to set priority bid?",
      icon: "question",
      showCancelButton: true,
      confirmButtonText: "Yes",
      cancelButtonText: "No",
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
    });

    if (result.isConfirmed) {
      try {
        const result = await dispatch(
          viewPrice({ amount, listing_id: listingId })
        );
        if (viewPrice.fulfilled.match(result)) {
          setShowPopup(false);
          setIsPriceUnlocked(true);
          toast.success("Reserve item unlocked successfully");
          await dispatch(viewListing({ id: id, user_id: CurrentUserID }));
          setTimeout(() => {
            setShowConfirmBuyPopup(true);
          }, 500);
        } else if (viewPrice.rejected.match(result)) {
          const error = String(
            result.payload || "Failed to unlock price. Please try again."
          );
          setErrorMessage(error);
        }
      } catch {
        setErrorMessage("An unexpected error occurred. Please try again.");
      }
    }
  };

  const handleBuyNow = (product: any) => {
    if (!product.view_price_status) {
      setSelectedProduct(product);
      setShowPopup(true);
    }
  };

  const navigateToAddWallet = () => {
    router.push("/profile/wallet/transaction/");
  };

  const handleDirectBuy = async (listing_id: any) => {
    if (!listing_id) {
      toast.error("Listing ID is missing!"); // Show error in toast
      return;
    }

    setIsLoading(true);
    setShowConfirmBuyPopup(false);

    try {
      const res = await dispatch(placeOrder({ listing_id })).unwrap();

      // Check if the order was successful
      if (!res.success) {
        toast.error(res.error || "An error occurred while placing your order.");
        return;
      }

      // If successful:
      setIsOrderPlaced(true);
      // setShowCongratulationPopup(true);
    } catch (error: any) {
      router.push("/");
      // Show API error in toast
      toast.error(error || "An error occurred while placing your order.");
    } finally {
      setIsLoading(false);
    }
  };

  const handleCategoryClick = async (id: number, name: string) => {
    const categoryName = name
      .replace(/[^a-zA-Z0-9\s]/g, "")
      .replace(/\s+/g, "-");
    router.push(`/${id}/${categoryName}`);
  };

  const selectedIndex = viewListingData?.images.indexOf(selectedImage) || 0;
  const currentTime = safeParseTime(
    settings?.current_time_formatted,
    "yyyy-MM-dd HH:mm:ss",
    userTimeZone
  );

  const auctionStartTime = viewListingData?.start_datetime
    ? DateTime.fromISO(viewListingData.start_datetime.replace(" ", "T"), {
        zone: userTimeZone,
      })
    : null;

  const isComingSoon = auctionStartTime && auctionStartTime > currentTime;

  useEffect(() => {
    const interval = setInterval(() => {
      dispatch(ongoingBids(id));
    }, 40000); // every 40 seconds

    return () => clearInterval(interval); // clean up on unmount
  }, [dispatch, id]);

  useEffect(() => {
    if (!id) return;

    const appKey = process.env.NEXT_PUBLIC_PUSHER_APP_KEY!;
    const cluster = process.env.NEXT_PUBLIC_PUSHER_APP_CLUSTER!;

    const createPusher = () => {
      const pusher = new Pusher(appKey, {
        cluster,
        forceTLS: true,
        enabledTransports: ["ws", "wss"],
      });

      const subscribe = () => {
        // Subscribe to listing.<id> for bid updates
        const bidChannel = pusher.subscribe(`listing.${id}`);
        bidChannel.bind("bid.placed", (data: any) => {
          const placedByUserID = data?.bid?.user_id;
          if (placedByUserID !== CurrentUserID) {
            toast.info("⚡ A new bid has been placed!", {
              toastId: `new-bid-${placedByUserID}`,
            });
          }
          dispatch(ongoingBids(id));
          dispatch(viewListing({ id, user_id: CurrentUserID }));
        });

        // Subscribe to reserve-order.<id> for reserve order updates
        const reserveChannel = pusher.subscribe(`reserve-order.${id}`);
        reserveChannel.bind("reserve.order.placed", (data: any) => {
          setAuctionEnded(true);
          setOrderData(data);
          toast.success("A new reserve order has been placed!", {
            toastId: `reserve-order-${id}`,
          });

          // You can dispatch additional actions here if needed
          dispatch(viewListing({ id, user_id: CurrentUserID }));
        });
      };

      pusher.connection.bind("state_change", ({ previous, current }) => {
        console.log(`Pusher connection state: ${previous} → ${current}`);
        if (current === "connected") {
          subscribe();
        }
      });

      pusher.connection.bind("disconnected", () => {
        console.warn("Pusher disconnected. Retrying...");
        setTimeout(() => {
          if (pusherRef.current) {
            pusherRef.current.disconnect();
          }
          pusherRef.current = createPusher();
        }, 3000);
      });

      subscribe();
      return pusher;
    };

    // Initial Pusher connection
    pusherRef.current = createPusher();

    return () => {
      console.log("Cleaning up Pusher...");
      if (pusherRef.current) {
        pusherRef.current.unsubscribe(`listing.${id}`);
        pusherRef.current.unsubscribe(`reserve-order.${id}`);
        pusherRef.current.disconnect();
        pusherRef.current = null;
      }
    };
  }, [id, dispatch, CurrentUserID]);

  useEffect(() => {
    if (typeof window !== "undefined" && viewListingData?.images?.length) {
      viewListingData.images.forEach((imgUrl: string) => {
        const preloadImg = new window.Image();
        preloadImg.src = imgUrl;
      });
    }
  }, [viewListingData?.images]);

  return (
    <>
      <div className="max-w-7xl m-auto">
        <div className="text-gray-600 md:pt-8 md:gap-2 xs:pt-4 lg:flex xl:flex xs:flex xs:px-4 flex-wrap">
          <Link
            href={`/`}
            className="text-gray-600 md:text-[1rem] xs:text-sm font-normal hover:text-yellow-500 flex "
          >
            Home {" > "}
          </Link>
          <div
            onClick={() =>
              handleCategoryClick(
                viewListingData?.category?.id,
                viewListingData?.category?.name
              )
            }
            className="text-gray-600 md:text-[1rem] xs:text-sm font-normal hover:text-yellow-500 cursor-pointer "
          >
            {viewListingData?.category?.name &&
              viewListingData?.category?.name + " > "}
          </div>

          <span className="md:text-[1rem] xs:text-sm font-normal capitalize text-[#F8CB1F] ">
            {""} {viewListingData?.product_name}
          </span>
        </div>

        <div className="lg:grid lg:grid-cols-12 gap-4 pt-6 xs:flex xs:flex-col-reverse">
          <div className="xl:col-span-4 lg:col-span-4 xs:col-span-12 lg:p-0 xs:p-4 flex flex-col">
            <div className="bg-white  xs:w-full xs:p-4 flex flex-col items-start pt-10 pb-10 sm:p-7 rounded-md">
              <div className="text-start w-full ">
                <div className="flex justify-between ">
                  <p className="text-black text-lg">Total Bids :</p>
                  <span className="text-lg font-bold text-black">
                    {viewListingData?.bid_count}
                  </span>
                </div>
                <div className="flex justify-between">
                  <p className="text-black text-lg">Current price :</p>
                  <span className="text-lg font-extrabold text-black flex flex-col">
                    {viewListingData?.currency === "CAD"
                      ? "C$"
                      : viewListingData?.currency === "USD"
                      ? "US$"
                      : ""}{" "}
                    {listingData?.data?.listing?.bids.length > 0
                      ? new Intl.NumberFormat("en-US", {
                          minimumFractionDigits: 2,
                          useGrouping: true,
                        }).format(listingData?.data?.listing?.bids[0]?.amount)
                      : new Intl.NumberFormat("en-US", {
                          minimumFractionDigits: 2,
                          useGrouping: true,
                        }).format(viewListingData?.starting_bid || 0)}
                    {currency != viewListingData?.currency && (
                      <span className="text-gray-400 text-sm text-right">
                        ( {viewListingData?.currency === "USD" ? "C$" : "US$"}{" "}
                        {convertCurrency(
                          parseFloat(
                            Number(
                              listingData?.data?.listing?.bids?.length > 0
                                ? listingData?.data?.listing?.bids[0]?.amount
                                : viewListingData?.starting_bid ?? 0
                            ).toFixed(3)
                          ),
                          viewListingData?.currency,
                          viewListingData?.currency === "USD" ? "CAD" : "USD",
                          rates
                        ).toFixed(2)}
                        )
                      </span>
                    )}
                  </span>
                </div>
                <div className="bg-[#f4f4f4] mt-1 p-2">
                  <div className="flex justify-between border-b border-gray-200">
                    <p className="text-black text-base">
                      {isComingSoon ? "Bidding starts in :" : "Time Left :"}
                    </p>

                    {viewListingData?.auction_ends_at ? (
                      <div className="text-red-500 xs:justify-start md:text-lg font-medium md:justify-end flex items-end space-x-1">
                        {orderData || viewListingData?.expired === 1 ? (
                          <span>00:00:00</span> // Show only when order is placed
                        ) : (
                          <AuctionTimer
                            useParentProps={false}
                            onAuctionEnd={() => {
                              if (!isComingSoon) {
                                setTimeout(() => {
                                  setAuctionEnded(true);
                                }, 5000); // 5 second delay
                              }
                            }}
                          />
                        )}
                      </div>
                    ) : null}

                    {auctionEnded && !loading && (
                      <AuctionResultPopup
                        ongoingData={ongoingData}
                        orderGenerateData={orderData}
                        currentUserID={CurrentUserID}
                        reservePrice={
                          Number(viewListingData?.reserve_price) || 0
                        }
                        SellerUserId={viewListingData?.user?.id}
                        onClose={() => setAuctionEnded(false)}
                      />
                    )}
                  </div>
                  <div className="flex justify-between border-b border-gray-200">
                    <p className="text-black  text-base">Item Status :</p>
                    <span className="text-lg text-black font-medium text-start">
                      {viewListingData?.product_type}
                    </span>
                  </div>
                  {viewListingData?.product_type === "Reserved" && (
                    <div className="flex text-black justify-between">
                      <p className="text-black text-base">Unlock Price Fee :</p>
                      <span className="text-lg font-medium">
                        {incrementData?.data?.auctionFee[0]?.unlock_fee}
                      </span>
                    </div>
                  )}
                </div>
              </div>

              <form className="w-full" onSubmit={handleSubmit}>
                <div className="flex flex-col mb-4">
                  <label
                    htmlFor="amount"
                    className="mb-2 text-xl text-black font-bold text-start mt-3"
                  >
                    Add Bid:
                  </label>

                  <div className="flex items-center  rounded-sm gap-2">
                    {/* Decrement Button */}
                    <button
                      type="button"
                      onClick={() =>
                        setAmount((prev: any) => {
                          const current =
                            prev ?? viewListingData?.max_bid_required ?? 0;
                          const minBid = viewListingData?.max_bid_required ?? 0;
                          const decrement = getIncrement(current, increments);

                          const next = current - decrement;
                          return next < minBid ? minBid : next;
                        })
                      }
                      className={`px-2 py-1 text-lg font-bold 
                                ${
                                  amount <=
                                  (viewListingData?.max_bid_required ?? 0)
                                    ? "bg-gray-300 cursor-not-allowed"
                                    : "bg-yellow-400 hover:bg-yellow-500"
                                }`}
                      disabled={
                        amount <= (viewListingData?.max_bid_required ?? 0)
                      }
                    >
                      −
                    </button>

                    <div className="relative w-full max-w-xs">
                      {/* Currency Prefix */}
                      <span className="absolute left-2 top-1/2 -translate-y-1/2 text-black font-semibold text-sm">
                        {viewListingData?.currency === "CAD"
                          ? "C$"
                          : viewListingData?.currency === "USD"
                          ? "$"
                          : ""}
                      </span>

                      {/* Input Field */}
                      <input
                        type="text"
                        id="amount"
                        value={
                          amount !== undefined
                            ? amount.toLocaleString("en-US")
                            : ""
                        }
                        onChange={handleChange}
                        className="w-full pl-10 pr-10 py-2 text-center focus:outline-none border border-gray-300 rounded"
                        placeholder="Enter price"
                      />

                      {/* Currency Suffix */}
                      <span className="absolute right-2 top-1/2 -translate-y-1/2 text-black font-semibold text-sm">
                        {viewListingData?.currency}
                      </span>
                    </div>

                    {/* Increment Button */}
                    <button
                      type="button"
                      onClick={() =>
                        setAmount((prev: any) => {
                          const current =
                            prev ?? viewListingData?.max_bid_required ?? 0;
                          const increment = getIncrement(current, increments);
                          return current + increment;
                        })
                      }
                      className="bg-yellow-400 px-2 py-1 text-lg font-bold hover:bg-yellow-500"
                    >
                      +
                    </button>
                  </div>

                  {/* Submit Button */}
                  <button
                    className={`mt-4 text-2xl font-bold p-3 bg-[#F8CB1F] text-black rounded-md hover:bg-[#E4B71C] focus:outline-none focus:ring-0 active:outline-none active:ring-0 w-full xs-full ${
                      CurrentUserID === userID ||
                      isComingSoon ||
                      viewListingData?.expired == 1 ||
                      auctionEnded
                        ? "pointer-events-none opacity-50"
                        : ""
                    }`}
                    type="submit"
                  >
                    {status === "loading" ? "Sending Bid..." : "Send Bid"}
                  </button>
                </div>
              </form>
              {/* Custom Modal for Bid Confirmation */}
              {isModalOpen &&
              Number(WalletBalance) > Number(AuctionSellerFee) ? (
                <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
                  <div className="bg-white p-6 rounded-md shadow-md w-28 m-2 ">
                    <p className="text-xl text-black mb-4 overflow-auto">
                      Are you sure you want to place bid for this auction for
                      amount: {formattedAmount}?
                    </p>
                    <div className="flex justify-center space-x-4">
                      <button
                        onClick={handleConfirm}
                        className="bg-green-500 text-white p-2 rounded"
                      >
                        Confirm
                      </button>
                      <button
                        onClick={() => {
                          setIsModalOpen(false);
                          setWasCancelled(true);
                        }}
                        className="bg-red-500 text-white p-2 rounded"
                      >
                        Cancel
                      </button>
                    </div>
                  </div>
                </div>
              ) : (
                <Popup
                  showPopup={isModalOpen}
                  message={
                    <div>
                      <p className="text-red-600">
                        Insufficient wallet balance
                      </p>
                      <p className="mt-2 text-gray-600">
                        You might need to add funds to your wallet.
                      </p>
                    </div>
                  }
                  onClose={() => {
                    // setErrorMessage(null);
                    setIsModalOpen(false);
                  }}
                  onConfirm={() => setIsModalOpen(false)}
                  onAddWallet={() => {
                    setIsModalOpen(false);
                    navigateToAddWallet();
                  }}
                  showAddWalletButton={true}
                />
              )}
              <div className="w-full">
                {ongoingData?.data?.bids?.length > 0 && (
                  <div className="flex justify-between items-center mb-4">
                    <h2 className="text-black text-xl font-bold">
                      Ongoing Bids
                    </h2>
                    <>
                      {/* Trigger Button */}
                      {isLoggedIn && (
                        <div
                          onClick={() => setIsListingBidsOpen(true)}
                          className="flex items-center gap-1 text-gray-500 text-sm cursor-pointer"
                        >
                          <FaInfoCircle className="text-2xl" />
                          <span className="text-gray-500 text-xl">Info</span>
                        </div>
                      )}

                      {/* Modal */}
                      {isListingBidsOpen && (
                        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 px-4 sm:px-6">
                          <div className="bg-white px-6 py-10 md:p-10   rounded-md shadow-xl h-[80vh] w-full max-w-6xl overflow-y-auto relative">
                            <button
                              onClick={() => setIsListingBidsOpen(false)}
                              className="absolute top-0 right-3 text-black font-normal cursor-pointer hover:text-gray-800 text-4xl p-0"
                            >
                              &times;
                            </button>
                            <ListingBids />
                          </div>
                        </div>
                      )}
                    </>
                  </div>
                )}
                <div>
                  {viewListingData?.bid_status === "outbid" ? (
                    <p className="text-red-500">
                      Outbid | You Bid:{" "}
                      {viewListingData?.currency === "CAD"
                        ? "C$"
                        : viewListingData?.currency === "USD"
                        ? "US$"
                        : ""}{" "}
                      {viewListingData?.user_bid_amount}
                    </p>
                  ) : viewListingData?.bid_status === "winning" ? (
                    <p className="text-green-600">
                      Winning | You Bid:{" "}
                      {viewListingData?.currency === "CAD"
                        ? "C$"
                        : viewListingData?.currency === "USD"
                        ? "US$"
                        : ""}{" "}
                      {viewListingData?.top_bid_amount}
                    </p>
                  ) : null}
                </div>
                <div className="bids-list max-h-72 capitalize outgoing-bids cursor-pointer">
                  {ongoingData?.data?.bids?.map((bid: any) => {
                    const maskedPhone = bid?.user?.phone
                      ? `** ${bid?.user?.phone.slice(-2)}`
                      : "N/A";
                    return (
                      <BidCard
                        key={bid.id}
                        phone={maskedPhone}
                        price={bid.amount}
                        formatDate={formatDate(bid.created_at)}
                        selectedCurrency={
                          viewListingData?.currency === "USD" ? "CAD" : "USD"
                        }
                        listedCurrency={viewListingData?.currency}
                        exchangeRates={rates}
                      />
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
          <div className="xl:col-span-8 lg:col-span-8 xs:col-span-12 xs:p-0 p-4 ">
            <div className=" lg:p-0 xs:p-4 ">
              <div className="bg-white rounded-lg md:p-7 xs:p-3 ">
                <div className="grid md:grid-cols-2 xs:grid-cols-1">
                  <div>
                    <h1 className="md:text-3xl xs:text-[1.5rem] font-semibold text-gray-900 mb-4 text-start capitalize ">
                      {viewListingData?.product_name}
                    </h1>
                    <div>
                      <p className="text-[#A2A2A1] text-start font-bold text-lg">
                        Posted {formatDate(viewListingData?.created_at)}
                      </p>
                    </div>
                  </div>

                  <div className="flex flex-col md:items-end mb-3">
                    {viewListingData?.product_type === "Reserved" ? (
                      <>
                        {viewListingData?.expired == 1 || auctionEnded ? (
                          // 🔴 Discard button shown only when expired
                          <button
                            onClick={() => router.push("/")}
                            className="bg-red-600 text-white px-6 py-2 rounded-md font-semibold text-sm hover:bg-red-700 transition-all"
                          >
                            Discard
                          </button>
                        ) : !isOrderPlaced ? (
                          // 🟡 UNLOCK RESERVE / Generate Order button
                          <Link
                            href="#"
                            onClick={(e) => {
                              e.preventDefault();

                              if (
                                CurrentUserID === userID ||
                                isComingSoon ||
                                Number(viewListingData?.bids?.[0]?.amount) >
                                  Number(viewListingData?.reserve_price)
                              ) {
                                return;
                              }

                              if (viewListingData.view_price_status) {
                                setSelectedProduct(viewListingData);
                                setShowConfirmBuyPopup(true);
                              } else {
                                handleBuyNow(viewListingData);
                              }
                            }}
                            className={`md:custom-button-price xs:custom-button-sm transition duration-300 ${
                              CurrentUserID === userID ||
                              isComingSoon ||
                              Number(viewListingData?.bids?.[0]?.amount) >
                                Number(viewListingData?.reserve_price)
                                ? "pointer-events-none opacity-50"
                                : ""
                            }`}
                          >
                            <span className="relative z-10 xs:text-xs font-semibold md:text-[0.900rem]">
                              {viewListingData.view_price_status
                                ? "Generate Order"
                                : "UNLOCK RESERVE"}
                            </span>
                          </Link>
                        ) : (
                          <p className="text-black font-bold mt-2">
                            Order Placed Successfully!
                          </p>
                        )}
                      </>
                    ) : (
                      viewListingData?.product_type === "Unreserved" &&
                      (viewListingData?.expired == 1 || auctionEnded) && (
                        //  Discard button shown only when expired or auction ended
                        <button
                          onClick={() => router.push("/")}
                          className="bg-red-600 text-white px-6 py-2 rounded-md font-semibold text-sm hover:bg-red-700 transition-all"
                        >
                          Discard
                        </button>
                      )
                    )}

                    {/* 💸 Unlock fee text – hide if expired */}
                    {viewListingData?.product_type === "Reserved" &&
                      !viewListingData.view_price_status &&
                      !isOrderPlaced &&
                      viewListingData?.expired !== 1 &&
                      !(
                        Number(viewListingData?.bids?.[0]?.amount) >
                        Number(viewListingData?.reserve_price)
                      ) && (
                        <p className="md:text-lg xs:text-sm text-gray-700 mt-1 text-start flex items-center gap-1">
                          {incrementData?.data?.auctionFee[0]?.unlock_fee?.endsWith(
                            "0.99"
                          ) ? (
                            <>
                              <Image
                                unoptimized
                                src={cents}
                                alt="cents"
                                width={20}
                                height={20}
                                className="h-5 w-auto object-contain"
                              />
                              <span className="font-bold text-gray-900">
                                {incrementData?.data?.auctionFee[0]
                                  ?.unlock_fee || 0}
                              </span>
                            </>
                          ) : (
                            <span className="font-bold text-gray-900">
                              {incrementData?.data?.auctionFee[0]?.unlock_fee ||
                                0}
                            </span>
                          )}{" "}
                          to unlock reserve
                        </p>
                      )}

                    {/* ✅ Reserve Met Message */}
                    {viewListingData?.product_type === "Reserved" &&
                      Number(viewListingData?.bids?.[0]?.amount) >
                        Number(viewListingData?.reserve_price) && (
                        <p className="md:text-lg xs:text-sm text-red-900 mt-1 text-start font-semibold">
                          Reserve has been met. Item will sell.
                        </p>
                      )}
                  </div>
                </div>
                <div className="grid md:grid-cols-2 xs:grid-col-1">
                  {viewListingData?.product_type === "Reserved" &&
                    viewListingData.view_price_status && (
                      <div className="mb-2 text-lg font-bold text-green-500 flex gap-2">
                        <span className="font-bold text-gray-700">
                          Reserve Price:
                        </span>
                        <div className="flex flex-col">
                          <span>
                            {viewListingData?.currency === "USD" ? "US$" : "C$"}{" "}
                            {viewListingData?.reserve_price}
                          </span>
                          {currency != viewListingData?.currency && (
                            <span className="text-gray-500 font-semibold text-base text-left">
                              {viewListingData?.currency === "USD"
                                ? "C$"
                                : "US$"}{" "}
                              {convertCurrency(
                                parseFloat(
                                  Number(
                                    viewListingData?.reserve_price
                                  ).toFixed(3)
                                ),
                                viewListingData?.currency,
                                viewListingData?.currency === "USD"
                                  ? "CAD"
                                  : "USD",
                                rates
                              ).toFixed(2)}
                            </span>
                          )}
                        </div>
                      </div>
                    )}
                </div>
                {viewListingData?.sub_location && (
                  <div className="grid">
                    <div className="mb-2 text-lg font-bold text-black flex gap-2 capitalize">
                      <span className="font-bold text-gray-700 capitalize">
                        Location:
                      </span>
                      {viewListingData?.full_address &&
                        viewListingData?.full_address + ", "}
                      {viewListingData?.sub_location}
                    </div>
                  </div>
                )}
                {isLoading && (
                  <div className="r inset-0 flex items-center justify-center bg-opacity-50 z-10 top-0 ">
                    <div className="loader2 left-[80%]"></div>
                  </div>
                )}

                <div className="grid md:grid-cols-2 xs:grid-cols-1 justify-between mt-5"></div>
                {/* Helmet for SEO & Social Media Meta Tags */}

                <div className="flex  gap-4 lg:flex-row  xs:flex-col relative">
                  <div className="social-icons lg:flex-col md:justify-start gap-5 xs:flex xs:justify-between xs:items-center xs:m-0">
                    <ClientShareButtons
                      url={productUrl}
                      title={metaTitle}
                      description={metaDescription}
                      isProductLiked={isProductLiked}
                      onToggleLike={() => toggleLike(productId)}
                    />
                  </div>
                  {!loading ? (
                    <div className="flex gap-6 lg:flex-row xs:flex-col">
                      <div className="flex items-center relative overflow-hidden">
                        {isComingSoon && (
                          <div className="absolute top-[2rem] left-[-2.1rem] w-[184px] transform -rotate-[39deg] bg-[#F8CB1F] text-black text-center text-[17px] tracking-[0.010em] font-bold pt-[0.10rem] pb-[0.15rem] z-10">
                            Coming Soon
                          </div>
                        )}
                        {selectedImage ? (
                          <Image
                            unoptimized
                            src={selectedImage}
                            alt="Selected"
                            width={556}
                            height={370}
                            className="lg:w-[556px] lg:max-h-[370px] h-full w-full md:max-w-full cursor-pointer object-cover rounded-[20px]"
                            onClick={() => handleImageClick(selectedImage)}
                          />
                        ) : null}
                      </div>
                      <div className="flex xs:flex-row lg:flex-col md:gap-5 xs:gap-3 overflow-auto md:max-h-[372px] scrollbar-none">
                        {viewListingData?.images.map(
                          (image: any, index: any) => (
                            <Image
                              unoptimized
                              key={index}
                              src={image}
                              alt={viewListingData.product_name}
                              width={150}
                              height={100}
                              className="md:max-w-[150px] md:max-h-[100px] xs:max-w-[170px] xs:h-[100px] mt-2 cursor-pointer md:rounded-[20px] xs:rounded-md object-cover"
                              onClick={() => handleImageClick(image)}
                            />
                          )
                        )}
                      </div>
                    </div>
                  ) : (
                    <div className="flex justify-center items-center">
                      <div className="loader2 absolute left-[50%] top-[50%]"></div>
                    </div>
                  )}

                  {/* Imported Image Modal */}
                  <ImageModal
                    isModalOpens={isModalOpens}
                    closeModal={closeModal}
                    selectedIndex={selectedIndex}
                    viewListingData={viewListingData}
                    handleImageClick={handleImageClick}
                  />
                </div>
              </div>

              {isLoggedIn && isPriceUnlocked && <PriorityBids />}

              {/* Unlock Price Button */}
              {isLoggedIn && viewListingData && !isPriceUnlocked && (
                <div className="container  p-4 bg-white rounded-md mt-4 xs:max-w-full">
                  <div className="flex justify-start">
                    <button
                      onClick={() =>
                        handleUnlockPriceWithConfirmation(
                          viewListingData?.reserve_price || 0,
                          viewListingData?.id
                        )
                      }
                      disabled={viewListingData?.expired === 1 || auctionEnded}
                      className={`
                        bg-[#F8CB1F] py-3 px-8 rounded-md relative flex h-[45px]
                        text-[1.1rem] items-center justify-center overflow-hidden font-semibold
                        text-black shadow-sm border border-gray-200 
                        hover:bg-white hover:text-black hover:border-gray-300
                        transition-all duration-300
                        ${
                          viewListingData?.expired == 1 || auctionEnded
                            ? "pointer-events-none opacity-50"
                            : ""
                        }
                      `}
                    >
                      Unlock Price
                    </button>
                  </div>
                  <div className="text-start mt-2">
                    <p className="text-sm text-gray-600">
                      Click to unlock the price and set priority bid
                    </p>
                  </div>
                </div>
              )}

              <div className="container mx-auto p-4 bg-white rounded-md mt-4 xs:max-w-full">
                <h1 className=" text-start text-3xl font-bold mb-4 text-black capitalize">
                  Overview
                </h1>

                <hr className="mt-6"></hr>

                <div className="grid lg:grid-cols-2 xs:gird-col-12 gap-4 mt-5">
                  <div className="text-start">
                    {viewListingData?.shipping_details &&
                      viewListingData?.shipping_details != "null" && (
                        <div className="mb-2 font-medium  text-black flex gap-2 capitalize ">
                          <span className="font-medium  text-gray-700 ">
                            Shipping details:
                          </span>{" "}
                          {viewListingData?.shipping_details}
                        </div>
                      )}
                    <div className="mb-2 font-medium  text-black flex gap-2  capitalize">
                      <span className="font-medium  text-gray-700">
                        Product Name:
                      </span>{" "}
                      {viewListingData?.product_name}
                    </div>
                    <div className="mb-2 font-medium  text-black flex gap-2  capitalize">
                      <span className="font-medium  text-gray-700">
                        Sale by:
                      </span>{" "}
                      {viewListingData?.sale_by}
                    </div>
                    {viewListingData?.vin_number &&
                      viewListingData?.vin_number != "null" && (
                        <>
                          <div className="mb-2 font-medium  text-black flex gap-2">
                            <span className="font-medium  text-gray-700">
                              VIN Number:
                            </span>{" "}
                            {viewListingData?.vin_number}
                          </div>
                          <div>
                            <button
                              onClick={handleCarfax}
                              disabled={
                                viewListingData?.expired === 1 || auctionEnded
                              }
                              className={`
                                        bg-[#F8CB1F] py-2 px-6 rounded-md relative flex h-[35px]
                                        text-[1rem] items-center justify-center overflow-hidden font-semibold
                                        text-black shadow-sm border border-gray-200 
                                        hover:bg-white hover:text-black hover:border-gray-300
                                        ${
                                          viewListingData?.expired == 1 ||
                                          auctionEnded
                                            ? "pointer-events-none opacity-50"
                                            : ""
                                        }
                                      `}
                            >
                              CHECK CARFAX REPORT
                            </button>

                            <p className="text-sm text-gray-400 pt-1">
                              VIN will be copied to clipboard when you click the
                              button.
                            </p>
                          </div>
                        </>
                      )}
                  </div>
                  <div className="text-start">
                    {viewListingData?.website_link && (
                      <div className="mb-2 font-medium text-black flex gap-2 items-center">
                        <span className="font-medium text-gray-700">
                          Website Link:
                        </span>
                        <a
                          href={viewListingData.website_link}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600  hover:text-blue-800 break-all"
                        >
                          {viewListingData.website_link}
                        </a>
                      </div>
                    )}
                    {viewListingData?.youtube_link && (
                      <div className="mb-2 font-medium text-black flex gap-2 items-center">
                        <span className="font-medium text-gray-700">
                          YouTube:
                        </span>
                        <a
                          href={viewListingData.youtube_link}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center gap-2 bg-red-600 text-white px-3 py-1 rounded hover:bg-red-700 transition text-sm"
                        >
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 24 24"
                            fill="currentColor"
                            className="w-5 h-5"
                          >
                            <path d="M19.615 3.184C21.034 3.603 21.5 5.08 21.5 7.583v8.834c0 2.504-.466 3.98-1.885 4.399C17.905 21.2 12 21.2 12 21.2s-5.905 0-7.615-.384C2.966 20.397 2.5 18.92 2.5 16.417V7.583c0-2.504.466-3.98 1.885-4.399C6.095 2.8 12 2.8 12 2.8s5.905 0 7.615.384ZM10 9.5v5l5-2.5-5-2.5Z" />
                          </svg>
                          Open Video
                        </a>
                      </div>
                    )}

                    {viewListingData?.fuel_type &&
                      viewListingData?.fuel_type != "null" && (
                        <div className="mb-2 font-medium  text-black flex gap-2  capitalize">
                          <span className="font-medium  text-gray-700">
                            Fuel Type:
                          </span>{" "}
                          {viewListingData?.fuel_type}
                        </div>
                      )}
                  </div>
                </div>
                <hr className="mt-8"></hr>
                <h2 className="text-3xl text-black font-bold mb-3 text-start mt-5 ">
                  Description
                </h2>
                <p className="text-lg text-gray-600 font-medium  capitalize text-justify whitespace-pre-wrap">
                  {viewListingData?.description}
                </p>
              </div>
            </div>
          </div>
        </div>
        <AuctionProduct />
      </div>
      {showPopup && selectedProduct !== null && (
        <Popup
          showPopup={showPopup}
          message={
            errorMessage ? (
              <div>
                <p className="text-red-600">{errorMessage}</p>
                <p className="mt-2 text-gray-600">
                  You might need to add funds to your wallet.
                </p>
              </div>
            ) : (
              <div>
                <p className="text-gray-900 font-semibold">
                  Are you sure you want to unlock the reserve price for{" "}
                  <span className="font-bold text-green-600">
                    {selectedProduct.product_name}
                  </span>
                  ? A total of
                  <span className="font-bold text-green-600">
                    {" "}
                    {incrementData?.data?.auctionFee[0]?.unlock_fee}{" "}
                  </span>
                  will be deducted from your wallet upon confirmation.
                </p>
              </div>
            )
          }
          onClose={() => {
            setErrorMessage(null);
            setShowPopup(false);
          }}
          onConfirm={() =>
            handleUnlockPrice(
              incrementData?.data?.auctionFee[0]?.unlock_fee,
              selectedProduct.id
            )
          }
          onAddWallet={() => {
            setShowPopup(false);
            navigateToAddWallet();
          }}
          showAddWalletButton={!!errorMessage}
        />
      )}
      {/* Buy Confirmation Popup */}
      {showConfirmBuyPopup && selectedProduct !== null && (
        <Popup
          showPopup={showConfirmBuyPopup}
          message={
            <div>
              <p className="text-gray-900 font-semibold">
                You have successfully unlocked the reserve price for{" "}
                <span className="font-bold text-green-600">
                  {selectedProduct.product_name}
                </span>
                . The price for this product is{" "}
                <span className="font-bold text-blue-600">
                  ${selectedProduct.reserve_price}
                </span>
                . Would you like to proceed with buying this product now?
              </p>
            </div>
          }
          onClose={() => setShowConfirmBuyPopup(false)}
          onConfirm={() => handleDirectBuy(selectedProduct.id)}
        />
      )}
    </>
  );
};

export default AuctionInfo;
