"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import Image from "next/image";
import heart from "../assets/heart_gray.png";
import love from "../assets/loveHeart1.png";
import TimerIcon from "../assets/TimeIcon.png";
import { Wishlist, DeleteWishlist, recommendData } from "../api/api";
import { RootState } from "../store";
import AuctionTimer from "../components/bayerProfile/pages/components/AuctionTimer";
import { DateTime } from "luxon";
import TimeAgo from "./TimeAgo";
import safeParseTime from "../utils/dateUtils";

function AuctionProduct() {
  const router = useRouter();
  const dispatch = useDispatch<any>();
  const params = useParams();
  const id = params?.id as string;
  const [wishlistLoading, setWishlistLoading] = useState<{
    [key: string]: boolean;
  }>({});

  const recommendListings = useSelector(
    (state: RootState) => state.RecommendReducer
  );

  const { state, country } = useSelector(
    (state: RootState) => state.locationReducer
  );
  const { userData } = useSelector((state: RootState) => state.loginReducer);
  const CurrentUserID = userData?.data?.user?.id;
  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const userTimeZone = homedata?.data?.settings.default_timezone || "UTC";

  useEffect(() => {
    if (id) {
      dispatch(
        recommendData({
          id,
          user_id: CurrentUserID,
          location: country == "CAN" ? "Canada" : "USA",
          sub_location: ["USA", "Canada"].includes(state) ? "" : state,
        })
      );
    }
  }, [dispatch, id, CurrentUserID, state, country]);

  const getProductUrl = (
    id: string | number,
    categoryName: string,
    productName: string
  ): string => {
    const formattedCategory = (
      categoryName?.replace(/[^a-zA-Z0-9\s]/g, "").replace(/\s+/g, "-") ||
      "default-category"
    ).toLowerCase();

    const formattedProduct = (
      productName?.replace(/[^a-zA-Z0-9\s]/g, "").replace(/\s+/g, "-") ||
      "default-product"
    ).toLowerCase();

    return `/auction/${id}/${formattedCategory}/${formattedProduct}`;
  };

  const handleWishlistToggle = async (
    productId: string | number,
    isInWishlist: boolean,
    productDataName: string,
    categoryName: string
  ) => {
    const productKey = String(productId);

    if (!CurrentUserID) {
      const returnUrl = getProductUrl(
        productKey,
        categoryName,
        productDataName
      );
      router.push(`/auth/login?callbackUrl=${encodeURIComponent(returnUrl)}`);
      return;
    }

    if (wishlistLoading[productKey]) return;

    setWishlistLoading((prev) => ({ ...prev, [productKey]: true }));

    try {
      if (isInWishlist) {
        await dispatch(DeleteWishlist(productKey)).unwrap();
        toast.success("Removed from wishlist!");
      } else {
        await dispatch(Wishlist(productKey)).unwrap();
        toast.success("Added to wishlist!");
      }

      dispatch(
        recommendData({
          id: id,
          user_id: CurrentUserID,
          location: country == "CAN" ? "Canada" : "USA",
          sub_location: ["USA", "Canada"].includes(state) ? "" : state,
        })
      );
    } catch {
      toast.error("An error occurred while updating the wishlist.");
    } finally {
      setWishlistLoading((prev) => ({ ...prev, [productKey]: false }));
    }
  };

  function formatStartDateTime(datetimeStr: string): string {
    if (!datetimeStr) return "";

    const [datePartRaw, timePartRaw] = datetimeStr.split(" ");
    const datePart = datePartRaw;
    const timePart = timePartRaw || "00:00:00";

    const fixDateFormat = (dateStr: string) => {
      if (dateStr.includes(" ") && !dateStr.includes("T")) {
        return dateStr.replace(" ", "T");
      }
      return dateStr;
    };

    const fullDateTimeStr = fixDateFormat(`${datePart} ${timePart}`);
    const dateObj = new Date(fullDateTimeStr);

    if (isNaN(dateObj.getTime())) return "";

    const timeFormatted = dateObj.toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: true,
    });

    return `${datePart} ${timeFormatted}`;
  }

  return (
    <div className="font-system">
      {recommendListings?.recommendListing?.data?.recommended.length > 0 && (
        <div className="bg-[#F8F9F9]">
          <div className="mx-auto lg:py-12 xs:py-2 xs:px-4 sm:py-7 lg:max-w-7xl md:max-w-3xl">
            <h2 className="md:text-4xl xs:text-2xl text-start font-semibold text-[#3D3D3D] mb-5">
              Recommended for you
            </h2>
            <div className="lg:mt-8 flex flex-wrap gap-8">
              {recommendListings?.recommendListing?.data?.recommended
                ?.slice(0, 3)
                .map((product: any) => {
                  // const currentTime = DateTime.fromFormat(product?.current_time_formatted, "yyyy-MM-dd HH:mm:ss", {
                  //   zone: userTimeZone,
                  // });
                  const currentTime = safeParseTime(
                    product?.current_time_formatted,
                    "yyyy-MM-dd HH:mm:ss",
                    userTimeZone
                  );

                  // Convert auction start time
                  const auctionStartTime = DateTime.fromISO(
                    product?.start_datetime?.replace(" ", "T"),
                    { zone: userTimeZone }
                  );
                  // Check if auction is coming soon
                  const isComingSoon = auctionStartTime > currentTime;
                  const productKey = String(product.id);

                  return (
                    <div
                      key={product.id}
                      className={`bg-white rounded-lg w-full lg:w-96 md:w-[21rem] transition-transform duration-300 hover:scale-105 overflow-hidden hover:shadow-lg cursor-pointer ${
                        isComingSoon ? "opacity-90" : ""
                      }`}
                    >
                      <div className="relative">
                        <div className="relative h-60 w-full overflow-hidden rounded-lg">
                          {product.images?.[0] ? (
                            <Image
                              unoptimized
                              onClick={() =>
                                router.push(
                                  getProductUrl(
                                    product.id,
                                    product.category?.name,
                                    product.product_name
                                  )
                                )
                              }
                              onMouseEnter={() =>
                                router.prefetch(
                                  getProductUrl(
                                    product.id,
                                    product.category?.name,
                                    product.product_name
                                  )
                                )
                              }
                              src={product.images[0]}
                              alt={product.imageAlt || "Product image"}
                              className={`h-full w-full object-cover object-center ${
                                isComingSoon ? "opacity-70" : ""
                              }`}
                              width={384}
                              height={240}
                            />
                          ) : (
                            <div className="h-full w-full bg-gray-200 flex items-center justify-center text-gray-500 text-sm">
                              No Image Available
                            </div>
                          )}

                          {isComingSoon && (
                            <div className="absolute inset-0 bg-gradient-to-b from-black/60 to-transparent flex flex-col items-center justify-center text-center text-white p-4 bg-black opacity-70">
                              <span className="text-[1.25rem] font-bold uppercase animate-pulse tracking-widest">
                                Coming Soon
                              </span>
                              <p className="text-base opacity-80">
                                Stay tuned! Items will be available soon.
                              </p>
                              <span className="text-base opacity-80">
                                {formatStartDateTime(product?.start_datetime)}
                              </span>
                            </div>
                          )}

                          <div
                            onMouseEnter={() => {
                              if (!CurrentUserID) {
                                const loginUrl = `/auth/login?callbackUrl=${encodeURIComponent(
                                  getProductUrl(
                                    product.id,
                                    product.category?.name,
                                    product.product_name
                                  )
                                )}`;
                                router.prefetch(loginUrl);
                              }
                            }}
                            onClick={() =>
                              !wishlistLoading[productKey] &&
                              handleWishlistToggle(
                                product.id,
                                product.is_in_wishlist,
                                product.product_name,
                                product?.category?.name
                              )
                            }
                            className={`absolute top-1 left-4 md:right-2 h-6 w-6 bg-white rounded-full flex items-center justify-center transition-transform duration-300 ${
                              wishlistLoading[productKey]
                                ? "opacity-50 cursor-not-allowed"
                                : "hover:scale-125"
                            }`}
                          >
                            <Image
                              unoptimized
                              src={product.is_in_wishlist ? love : heart}
                              alt="Wishlist icon"
                              width={16}
                              height={16}
                              className="h-3 w-3 text-white cursor-pointer p-0"
                            />
                          </div>
                        </div>
                        <div>
                          {(product.bid_status === "winning" ||
                            product.bid_status === "outbid") && (
                            <button
                              className={`${
                                product.bid_status === "winning"
                                  ? "bg-green-900"
                                  : "bg-red-700"
                              } text-white absolute md:right-4 top-[200px] left-1 text-sm  font-semibold md:px-2 md:py-1 xs:px-1 rounded-md shadow-md flex items-center justify-center gap-1  text-center xs:p-1 w-20`}
                            >
                              {product.bid_status === "winning"
                                ? "Winning"
                                : "Outbid"}
                            </button>
                          )}
                        </div>

                        <div className="flex space-x-6">
                          <div className="flex flex-col mt-2 text-left w-full">
                            <div className="flex flex-col text-xs gap-1 p-3 font-semibold text-gray-400">
                              <h3 className="text-lg font-bold text-gray-900 capitalize truncate">
                                {product.product_name}
                              </h3>

                              <div className="flex justify-between mt-2">
                                <div
                                  onClick={() =>
                                    router.push(
                                      getProductUrl(
                                        product.id,
                                        product.category?.name,
                                        product.product_name
                                      )
                                    )
                                  }
                                  onMouseEnter={() =>
                                    router.prefetch(
                                      getProductUrl(
                                        product.id,
                                        product.category?.name,
                                        product.product_name
                                      )
                                    )
                                  }
                                  className="md:custom-button-price xs:custom-button-sm"
                                >
                                  <span className="relative z-10 xs:text-xs font-semibold md:text-[0.900rem]">
                                    VIEW
                                  </span>
                                </div>

                                {!isComingSoon && (
                                  <p className="font-bold text-md mt-4 text-gray-500 hidden md:block">
                                    <TimeAgo timestamp={product.created_at} />
                                  </p>
                                )}
                              </div>

                              {!isComingSoon && (
                                <div className="absolute md:right-4 top-[225px] bg-white xs:right-4 text-red-500 text-sm font-semibold md:px-2 md:py-1 xs:px-1 rounded-md shadow-md flex items-center flex-col space-x-1 ">
                                  {product.top_bid_amount && (
                                    <div className="text-red-500 md:text-base xs:text-[0.750rem]">
                                      Current Bid :{" "}
                                      {product?.currency === "CAD"
                                        ? "C$"
                                        : product?.currency === "USD"
                                        ? "US$"
                                        : ""}{" "}
                                      {product.top_bid_amount}
                                    </div>
                                  )}
                                  <div className="flex gap-1 items-center">
                                    <Image
                                      unoptimized
                                      src={TimerIcon}
                                      alt="Timer Icon"
                                      width={16}
                                      height={16}
                                      className="h-4 w-4"
                                    />
                                    <span className="text-base">
                                      <AuctionTimer
                                        auctionEndsAt={product.auction_ends_at}
                                        currentServerTime={
                                          product?.current_time_formatted
                                        }
                                      />
                                    </span>
                                  </div>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default AuctionProduct;
