"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import heart from "../../../../assets/heart_gray.png";
import love from "../../../../assets/loveHeart1.png";
import rightArrow from "../../../../assets/right-arrow-svgrepo-com.svg";
import leftArrow from "../../../../assets/left-arrow-svgrepo-com.svg";
import TimerIcon from "../../../../assets/TimeIcon.png";
import Auction from "../../../../assets/Auctions.svg";
import Sort from "../../../../assets/Sort.png";
import { useDispatch } from "react-redux";
import { auctionListing, Wishlist, DeleteWishlist } from "../../../../api/api";
import { RootState } from "../../../../store";
import { useSelector } from "react-redux";
import "../../../style.css";
import AuctionTimer from "../../../bayerProfile/pages/components/AuctionTimer";
import { toast } from "react-toastify";
import Image from "next/image";
import { DateTime } from "luxon";
import TimeAgo from "../../../../common/TimeAgo";

import {
  Menu,
  Transition,
  MenuItem,
  MenuItems,
  MenuButton,
} from "@headlessui/react";
import { clearLocation, setLocation } from "../../../../slice/LocationSlice";
import { useRouter } from "next/navigation";

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

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

  return `/auction/${id}/${formattedCategoryName}/${formattedProductName}`;
};

function AuctionListings() {
  const isInitialLoad = useRef(true);
  const router = useRouter();
  const dispatch = useDispatch<any>();
  const auctionState = useSelector(
    (state: RootState) => state.AllListingReducer
  );
  const { userData } = useSelector((state: RootState) => state.loginReducer);
  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const settings = homedata?.data?.settings;
  const userTimeZone = settings?.default_timezone || "UTC";

  const currency = useSelector(
    (state: any) => state.CurrencyReducer.selectedCurrency
  );

  const { latitude, longitude, state, country } = useSelector(
    (state: RootState) => state.locationReducer
  );
  const CurrentUserID = userData?.data?.user?.id;
  const lastPage = auctionState?.auctionList?.data?.last_page;
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [sortType, setSortType] = useState("Most recent");
  const [listings, setListings] = useState(
    auctionState?.auctionList?.data?.listings || []
  );
  console.log("check listing time");
  const [wishlistLoading, setWishlistLoading] = useState<{
    [key: string]: boolean;
  }>({});

  const [selectedAuctionType, setSelectedAuctionType] = useState<
    "live" | "upcoming"
  >("live");
  const isLoading = useSelector(
    (state: RootState) => state.AllListingReducer.loading
  );

  const handleAuctionTypeChange = (type: "live" | "upcoming") => {
    setSelectedAuctionType(type);
  };

  const handleRedirection = (
    id: number,
    categoryName: string,
    productName: string
  ) => {
    const route = getFormattedRoute(id, categoryName, productName);
    router.push(route);
  };

  const sortListings = (order: string) => {
    const sortedListings = [...listings].sort((a, b) => {
      if (order === "Most recent") {
        return (
          new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
        );
      } else if (order === "least recent") {
        return (
          new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
        );
      } else if (order === "Distance") {
        return a.distance - b.distance;
      }
      return 0;
    });
    setListings(sortedListings);
  };

  const fetchListings = useCallback(
    async (page: number) => {
      try {
        let latitude_data: string | undefined;
        let longitude_data: string | undefined;
        let stateName: string | null = null;

        const savedLocation = JSON.parse(
          localStorage.getItem("location") || "{}"
        );
        const userSelectedLocation =
          localStorage.getItem("userSelectedLocation") === "true";

        const isLoggedIn = !!CurrentUserID;

        if (isLoggedIn) {
          if (
            userSelectedLocation &&
            savedLocation?.latitude &&
            savedLocation?.longitude &&
            savedLocation?.state
          ) {
            latitude_data = savedLocation.latitude;
            longitude_data = savedLocation.longitude;
            stateName = savedLocation.state;
          } else if (latitude && longitude && state) {
            latitude_data = latitude;
            longitude_data = longitude;
            stateName = state;
          }
        } else {
          if (
            userSelectedLocation &&
            savedLocation?.latitude &&
            savedLocation?.longitude &&
            savedLocation?.state
          ) {
            latitude_data = savedLocation.latitude;
            longitude_data = savedLocation.longitude;
            stateName = savedLocation.state;
          }
        }

        const params: any = {
          page,
          CurrentUserID,
          currency,
          order_type: selectedAuctionType,
        };

        if (latitude_data && longitude_data) {
          params.latitude = latitude_data;
          params.longitude = longitude_data;
        }

        params.subLocation = stateName || "";

        const result = await dispatch(auctionListing(params));
        setListings(result?.payload?.data?.listings || []);
        setCurrentPage(page);
      } catch {
        // console.error("Error fetching listings:", error);
        return null;
      }
    },
    [
      dispatch,
      CurrentUserID,
      currency,
      latitude,
      longitude,
      state,
      selectedAuctionType,
    ]
  );
  useEffect(() => {
    const routesToPrefetch = ["/auth/login"];

    routesToPrefetch.forEach((route) => {
      router.prefetch(route);
    });
  }, [router]);
  
  useEffect(() => {
    const savedLocation = JSON.parse(localStorage.getItem("location") || "{}");
    const userSelectedLocation =
      localStorage.getItem("userSelectedLocation") === "true";

    if (
      userSelectedLocation &&
      savedLocation?.latitude &&
      savedLocation?.longitude &&
      savedLocation?.state
    ) {
      dispatch(setLocation(savedLocation));
    }

    fetchListings(1);
  }, [dispatch, userData, fetchListings]);

  useEffect(() => {
    setListings(auctionState?.auctionList?.data?.listings || []);
  }, [currency, auctionState?.auctionList?.data?.listings]);

  useEffect(() => {
    if (isInitialLoad.current) {
      isInitialLoad.current = false;
      return;
    }
    fetchListings(1);
  }, [
    latitude,
    longitude,
    CurrentUserID,
    currency,
    selectedAuctionType,
    fetchListings,
  ]);

  const handleWishlistToggle = async (
    productId: string,
    isInWishlist: boolean
  ) => {
    if (!CurrentUserID) {
      router.push("/auth/login");
      return;
    }

    // Prevent duplicate clicks while API is in progress
    if (wishlistLoading[productId]) return;

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

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

      setListings((prevListings: any) =>
        prevListings.map((product: any) =>
          product.id === productId
            ? { ...product, is_in_wishlist: !isInWishlist }
            : product
        )
      );
    } catch {
      toast.error("An error occurred while updating the wishlist.");
    } finally {
      setWishlistLoading((prev) => ({ ...prev, [productId]: false }));
    }
  };

  const handlePageChange = async (page: number) => {
    if (page < 1 || page > lastPage) return;
    try {
      const result = await dispatch(
        auctionListing({
          page,
          CurrentUserID,
          currency,
          order_type: selectedAuctionType,
          subLocation: "",
        })
      );
      setListings(result.payload?.data?.listings || []);
      setCurrentPage(page);
      window.scrollTo(0, 950);
    } catch {
      // console.error("Error fetching listings:", error);
      return null;
    }
  };

  const handleSortChange = (order: string) => {
    sortListings(order);
    setSortType(order);
  };

  const viewMore = async () => {
    if (currentPage < lastPage) {
      const nextPage = currentPage + 1;
      try {
        const result = await dispatch(
          auctionListing({
            page: nextPage,
            CurrentUserID,
            currency,
            order_type: selectedAuctionType,
            subLocation: "",
          })
        );
        setListings((prevListings: any) => [
          ...prevListings,
          ...result.payload.data.listings,
        ]);
        setCurrentPage(nextPage);
      } catch {
        // console.error("Error fetching listings:", error);
        return null;
      }
    }
  };
  const handleBack = () => {
    // Clear location data
    dispatch(clearLocation());
    localStorage.removeItem("location");
    fetchListings(1);
  };

  const sortOptions = [
    { name: "Most recent", value: "Most recent" },
    { name: "Least recent", value: "least recent" },
    // { name: "Distance", value: "Distance" },
  ];

  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())) {
      // console.error("Invalid date format in formatStartDateTime:", datetimeStr);
      return "";
    }

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

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

  useEffect(() => {
    dispatch(
      auctionListing({
        page: 1,
        CurrentUserID,
        currency,
        order_type: selectedAuctionType,
        subLocation: "",
      })
    );
  }, [dispatch, CurrentUserID, currency, selectedAuctionType]);

  return (
    <>
      <div className="font-system lg:mt-20 bg-[#F8F9F9]">
        <div className="mx-auto lg:py-12 xs:py-2 xs:px-4 sm:py-14 lg:max-w-7xl md:max-w-3xl md:m-auto">
          {/* Section Heading */}
          <h2 className="lg:text-4xl md:text-2xl xs:text-xl text-start md:pl-0 xs:pl-6 xs:pb-2 font-bold text-gray-800 font-inter-tight mb-3 lg:mt-24 xs:mt-1">
            {selectedAuctionType === "live"
              ? "Live Marketplace Auctions"
              : "Upcoming Auctions"}
          </h2>

          {/* Toggle Buttons & Sort */}
          <div className="flex flex-col md:flex-row items-center justify-between py-4">
            {/* Toggle Buttons */}
            <div className="flex space-x-2 p-2 xs:p-0 xs:pb-3 rounded">
              {["live", "upcoming"].map((type) => (
                <button
                  key={type}
                  onClick={() =>
                    handleAuctionTypeChange(type as "live" | "upcoming")
                  }
                  className={`px-2 py-2 rounded border md:text-base xs:text-[0.800rem] font-semibold ${
                    selectedAuctionType === type
                      ? "bg-yellow-400 text-black border-yellow-400"
                      : "bg-white text-black border-yellow-400"
                  }`}
                >
                  {type === "live"
                    ? "Live Marketplace Auctions"
                    : "Upcoming Auctions"}
                </button>
              ))}
            </div>

            {/* Sort Dropdown */}
            <Menu as="div" className="relative inline-block text-left ">
              <MenuButton className="border border-gray-300 rounded-full px-4 py-2 flex items-center gap-2 text-sm font-medium text-gray-700 hover:text-gray-900">
                <Image
                  unoptimized
                  src={Sort}
                  alt="Icon"
                  className="w-4 h-4 text-gray-500 group-hover:text-gray-700"
                  width={16}
                  height={16}
                />
                <span>
                  {sortOptions.find((opt) => opt.value === sortType)?.name}
                </span>
                <svg
                  className="w-4 h-4"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fillRule="evenodd"
                    d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
                    clipRule="evenodd"
                  />
                </svg>
              </MenuButton>
              <Transition
                enter="transition ease-out duration-100"
                enterFrom="transform opacity-0 scale-95"
                enterTo="transform opacity-100 scale-100"
                leave="transition ease-in duration-75"
                leaveFrom="transform opacity-100 scale-100"
                leaveTo="transform opacity-0 scale-95"
              >
                <MenuItems className="absolute z-10 mt-2 w-40 bg-white rounded-md divide-y shadow-2xl ring-1 overflow-hidden ring-black ring-opacity-5 focus:outline-none overflow-hidden">
                  {sortOptions.map((option) => (
                    <MenuItem key={option.value}>
                      {({ active }) => (
                        <div
                          onClick={() => handleSortChange(option.value)}
                          className={`block w-full text-left px-4 py-3 text-sm font-medium cursor-pointer text-gray-900 ${
                            // active || sortType === option.value
                            active
                              ? "bg-navy text-white dark:bg-gray-600"
                              : "text-gray-900 dark:text-white"
                          }`}
                        >
                          {option.name}
                        </div>
                      )}
                    </MenuItem>
                  ))}
                </MenuItems>
              </Transition>
            </Menu>
          </div>

          {/* Location Filter Info */}
          {state && (
            <div className="flex items-center justify-between mt-4">
              <div className="text-start">
                <p className="text-black font-medium md:text-xl">
                  Country:{" "}
                  <span className="text-gray-600 text-lg font-semibold">
                    {country === "CAN" ? "Canada" : "USA"}
                  </span>
                </p>
                <p className="text-black font-medium md:text-xl">
                  Province/State:{" "}
                  <span className="text-gray-600 text-lg font-semibold">
                    {state}
                  </span>
                </p>
              </div>
              <button
                onClick={handleBack}
                className="text-xl font-medium flex gap-1 items-center text-black"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  strokeWidth={1.5}
                  stroke="currentColor"
                  className="size-6"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M15.75 19.5 8.25 12l7.5-7.5"
                  />
                </svg>
                Show All Ads
              </button>
            </div>
          )}

          {/* Auction Listings or Fallback */}
          {isLoading ? (
            <div className="text-center ">Loading...</div>
          ) : listings?.length > 0 ? (
            <>
              {/* Listings */}
              <div className="lg:mt-8 grid xs:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xs:gap-3 md:gap-10">
                {listings.map((product: any) => {
                  const currentTime = product?.current_time_formatted
                    ? DateTime.fromFormat(
                        product.current_time_formatted,
                        "yyyy-MM-dd HH:mm:ss",
                        {
                          zone: userTimeZone,
                        }
                      )
                    : DateTime.now().setZone(userTimeZone); // Fallback to current time

                  const auctionStartTime = product?.start_datetime
                    ? DateTime.fromISO(
                        product.start_datetime.replace(" ", "T"),
                        {
                          zone: userTimeZone,
                        }
                      )
                    : DateTime.now().setZone(userTimeZone); // Fallback to current time

                  const isComingSoon = auctionStartTime > currentTime;

                  return (
                    <div
                      key={product.id}
                      className={`relative bg-white rounded-lg w-full cursor-pointer transition-transform duration-300 hover:scale-105 hover:shadow-lg overflow-hidden ${
                        isComingSoon ? "opacity-90" : ""
                      }`}
                    >
                      {/* Product Image */}
                      <div className="relative xs:h-24 md:h-60 w-full overflow-hidden rounded-lg">
                        {product.images[0] ? (
                          <div className="relative h-full w-full">
                            <Image
                              unoptimized
                              src={product.images[0]}
                              alt="product-image"
                              onClick={() =>
                                handleRedirection(
                                  product.id,
                                  product.product_name,
                                  product?.category?.name
                                )
                              }
                              onMouseEnter={() => {
                                const route = getFormattedRoute(
                                  product.id,
                                  product?.category?.name,
                                  product.product_name
                                );
                                router.prefetch(route);
                              }}
                              className="h-full w-full object-cover"
                              fill
                              sizes="400px"
                              priority
                            />
                          </div>
                        ) : (
                          <div className="h-full w-full bg-gray-100 flex items-center justify-center text-gray-500 text-sm">
                            No Image
                          </div>
                        )}

                        {/* Coming Soon Overlay */}
                        {isComingSoon && (
                          <div
                            onClick={() =>
                              handleRedirection(
                                product.id,
                                product.product_name,
                                product?.category?.name
                              )
                            }
                            onMouseEnter={() => {
                              const route = getFormattedRoute(
                                product.id,
                                product?.category?.name,
                                product.product_name
                              );
                              router.prefetch(route);
                            }}
                            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-80"
                          >
                            <span className="md:text-[1.25rem] xs:text-[0.800rem] font-bold uppercase animate-pulse">
                              Coming Soon
                            </span>
                            <p className="md:text-base xs:text-[0.700rem]">
                              Stay tuned! Items will be available soon.
                            </p>
                            <span className="md:text-base xs:text-[0.700rem]">
                              {formatStartDateTime(product?.start_datetime)}
                            </span>
                          </div>
                        )}

                        {/* Wishlist Icon */}
                        <div
                          onClick={() =>
                            !wishlistLoading[product.id] &&
                            handleWishlistToggle(
                              product.id,
                              product.is_in_wishlist
                            )
                          }
                          className="absolute top-1 h-6 w-6 left-1 md:left-4 md:top-2 bg-white rounded-full p-1 flex items-center justify-center hover:scale-125 transition-transform"
                        >
                          <Image
                            unoptimized
                            src={product.is_in_wishlist ? love : heart}
                            alt="Icon"
                            className="xs:h-2 xs:w-2 md:h-3 md:w-3 text-white cursor-pointer p-0"
                            width={12}
                            height={12}
                          />
                        </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 md:top-[200px] left-1 md:text-sm xs:text-[10px] font-semibold md:px-2 md:py-1 xs:px-1 rounded-md shadow-md flex items-center justify-center gap-1 top-[70px] text-center xs:p-1 md:w-20`}
                          >
                            {product.bid_status === "winning"
                              ? "Winning"
                              : "Outbid"}
                          </button>
                        )}
                      </div>
                      {!isComingSoon && (
                        <div
                          className="block md:hidden text-red-500 text-sm font-semibold md:px-2 md:py-1 xs:px-1  flex-col gap-1"
                          aria-hidden="true"
                        >
                          {product.top_bid_amount && (
                            <div className="text-red-500 md:text-base xs:text-[0.750rem]">
                              Current Bid NXC[o] :{" "}
                              {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"
                              className="md:h-4 md:w-4 xs:h-3"
                              width={16}
                              height={16}
                            />
                            <span className="md:text-base xs:text-[0.750rem]">
                              <AuctionTimer
                                auctionEndsAt={product?.auction_ends_at}
                                currentServerTime={
                                  product?.current_time_formatted
                                }
                              />
                            </span>
                          </div>
                        </div>
                      )}
                      {/* Product Info */}
                      <div className="px-3 pb-2">
                        <h3 className="text-lg font-bold text-gray-900 capitalize truncate text-start py-1">
                          {product.product_name}
                        </h3>
                        <div className="flex justify-between mt-2">
                          <button
                            onClick={() =>
                              handleRedirection(
                                product.id,
                                product.product_name,
                                product?.category?.name
                              )
                            }
                            onMouseEnter={() => {
                              const route = getFormattedRoute(
                                product.id,
                                product?.category?.name,
                                product.product_name
                              );
                              router.prefetch(route);
                            }}
                            className="md:custom-button-price xs:custom-button-sm"
                          >
                            <span className="z-10 xs:text-xs md:text-sm font-semibold">
                              VIEW
                            </span>
                          </button>
                          {!isComingSoon && (
                            <p className="font-bold text-xs mt-4 text-gray-500 hidden md:block">
                              <TimeAgo timestamp={product.created_at} />
                            </p>
                          )}
                        </div>
                        {!isComingSoon && (
                          <div
                            className="hidden md:flex absolute md:right-4 md:top-[225px] bg-white right-1 text-red-500 text-sm font-semibold md:px-2 md:py-1 xs:px-1 rounded-md shadow-md items-center flex-col gap-1"
                            aria-hidden="true"
                          >
                            {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"
                                className="md:h-4 md:w-4 xs:h-3"
                                width={16}
                                height={16}
                              />
                              <span className="md:text-base xs:text-[0.750rem]">
                                <AuctionTimer
                                  auctionEndsAt={product?.auction_ends_at}
                                  currentServerTime={
                                    product?.current_time_formatted
                                  }
                                />
                              </span>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Load More Button */}
              <div className="flex justify-center mt-8">
                <button
                  onClick={viewMore}
                  disabled={currentPage === lastPage}
                  className="text-gray-800 bg-customYellow py-1 px-5 rounded-sm font-semibold"
                >
                  {currentPage < lastPage ? "Load More" : "No More Listings"}
                </button>
              </div>

              {/* Pagination */}
              <div className="flex justify-center items-center space-x-2 mt-8 text-black">
                <button
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={currentPage === 1}
                  className="p-2 bg-gray-200 rounded disabled:opacity-50"
                >
                  <Image
                    unoptimized
                    src={leftArrow}
                    alt="leftArrow"
                    className="h-3 cursor-pointer text-black"
                    width={12}
                    height={12}
                  />{" "}
                </button>
                {Array.from({ length: lastPage }, (_, i) => i + 1).map(
                  (pageNum) => (
                    <button
                      key={pageNum}
                      onClick={() => handlePageChange(pageNum)}
                      className={`px-3 py-1 rounded ${
                        currentPage === pageNum
                          ? "bg-customYellow text-gray-800"
                          : "bg-white text-gray-600"
                      }`}
                    >
                      {pageNum}
                    </button>
                  )
                )}
                <button
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={currentPage === lastPage}
                  className="p-2 bg-gray-200 rounded disabled:opacity-50"
                >
                  <Image
                    unoptimized
                    src={rightArrow}
                    alt="arrow"
                    className="h-3 cursor-pointer text-black"
                    width={12}
                    height={12}
                  />
                </button>
              </div>
            </>
          ) : (
            // No listings found
            <div className="text-center mt-16">
              <Image
                unoptimized
                src={Auction}
                alt="No Listings Available"
                className="w-[1200px] md:pb-10 xs:px-4 xs:py-4"
              />
            </div>
          )}
        </div>
      </div>
    </>
  );
}

export default AuctionListings;
