"use client";

import { useEffect, useState } from "react";
import AuctionTimer from "../../../components/bayerProfile/pages/components/AuctionTimer";
import heroUnion from "../../../assets/category.png";
import Image from "next/image";
import { RootState } from "../../../store";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import TimerIcon from "../../../assets/TimeIcon.png";
import rightArrow from "../../../assets/right-arrow-svgrepo-com.svg";
import leftArrow from "../../../assets/left-arrow-svgrepo-com.svg";
import { searchListing, categoryApiCall } from "../../../api/api";
import Sort from "../../../assets/Sort.png";
import heart from "../../../assets/heart_gray.png";
import { DateTime } from "luxon";

import {
  Menu,
  MenuButton,
  MenuItems,
  MenuItem,
  Transition,
} from "@headlessui/react";
import love from "../../../assets/loveHeart1.png";
import { useParams, useRouter } from "next/navigation";
import { toast } from "react-toastify";
import { Wishlist, DeleteWishlist } from "../../../api/api";
import TimeAgo from "../../../common/TimeAgo";

function classNames(...classes: any) {
  return classes.filter(Boolean).join(" ");
}

const CategoryList = () => {
  const router = useRouter();
  const dispatch = useDispatch<any>();
  const params = useParams();
  const categoryId = params?.categoryId as string;

  const searchListState = useSelector(
    (state: RootState) => state.searchReducer
  );
  const [listings, setListings] = useState(
    searchListState?.searchList?.data?.listings || []
  );
  const { userData } = useSelector((state: RootState) => state.loginReducer);
  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const userTimeZone = homedata?.data?.settings.default_timezone || "UTC";
  const { categories } = useSelector(
    (state: RootState) => state.CategoryListing
  );
  const CurrentUserID = userData?.data?.user?.id;
  const lastPage = searchListState?.searchList?.data?.last_page;
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [sortType, setSortType] = useState("Most recent");
  const savedLocation = localStorage.getItem("location");
  const location = useSelector((state: RootState) => state.locationReducer);

  const getFormattedCategoryRoute = (
    categoryId: number,
    categoryName: string
  ) => {
    const formattedCategoryName =
      categoryName
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase() || "default-category";
    return `/${categoryId}/${formattedCategoryName}`;
  };

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

  const handleWishlistToggle = async (
    productId: string,
    isInWishlist: boolean,
    productDataName: string,
    categoryName: string
  ) => {
    try {
      let lat;
      let lon;
      let location;
      let subLocation;
      if (savedLocation) {
        const parsedLocation = JSON.parse(savedLocation);
        lat = parsedLocation?.latitude;
        lon = parsedLocation?.longitude;
        location = parsedLocation?.country == "US" ? "USA" : "Canada";
        subLocation =
          parsedLocation?.state == "USA" || parsedLocation?.state == "Canada"
            ? ""
            : parsedLocation?.state;
      }
      if (!CurrentUserID) {
        const formattedCategoryName = categoryName
          ?.replace(/[^a-zA-Z0-9\s]/g, "")
          .replace(/\s+/g, "-")
          .toLowerCase();
        const returnUrl = `/${categoryId}/${formattedCategoryName}`;
        router.push(`/auth/login?callbackUrl=${encodeURIComponent(returnUrl)}`);
        return;
      }
      if (isInWishlist) {
        await dispatch(DeleteWishlist(productId)).unwrap();
        toast.success("Removed from wishlist!");
      } else {
        await dispatch(Wishlist(productId)).unwrap();
        toast.success("Added to wishlist!");
      }
      await dispatch(
        searchListing({
          keyword: "",
          category_id: categoryId,
          page: 1,
          user_id: CurrentUserID,
          location_longitude: lat,
          location_latitude: lon,
          location: location || "",
          sub_location: subLocation || "",
        })
      );
    } catch {
      toast.error("An error occurred while updating the wishlist.");
    }
  };

  const sortListings = (order: string) => {
    const currentTime = new Date().getTime();

    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;
      } else if (order === "Coming soon") {
        const aComingSoon = new Date(a.start_datetime).getTime() > currentTime;
        const bComingSoon = new Date(b.start_datetime).getTime() > currentTime;
        if (aComingSoon && !bComingSoon) return -1;
        if (!aComingSoon && bComingSoon) return 1;
        return 0;
      }
      return 0;
    });

    setListings(sortedListings);
  };

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

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

    router.push(
      `/auction/${id}/${formattedCategoryName}/${formattedProductName}`
    );
  };

  const handlePageChange = async (page: number) => {
    if (page < 1 || page > lastPage) return;
    try {
      let lat;
      let lon;
      let location;
      let subLocation;
      if (savedLocation) {
        const parsedLocation = JSON.parse(savedLocation);
        lat = parsedLocation?.latitude;
        lon = parsedLocation?.longitude;
        location = parsedLocation?.country == "US" ? "USA" : "Canada";
        subLocation =
          parsedLocation?.state == "USA" || parsedLocation?.state == "Canada"
            ? ""
            : parsedLocation?.state;
      }
      const result = await dispatch(
        searchListing({
          keyword: "",
          category_id: categoryId,
          page: 1,
          user_id: CurrentUserID,
          location_longitude: lat,
          location_latitude: lon,
          location: location,
          sub_location: subLocation,
        })
      );
      if (searchListing.fulfilled.match(result)) {
        setListings(result?.payload?.data?.listings);
        setCurrentPage(page);
        window.scrollTo(0, 950);
      }
    } catch {
      return null;
    }
  };

  useEffect(() => {
    let lat;
    let lon;
    let location;
    let subLocation;

    if (savedLocation) {
      const parsedLocation = JSON.parse(savedLocation);
      lat = parsedLocation?.latitude;
      lon = parsedLocation?.longitude;
      location = parsedLocation?.country == "US" ? "USA" : "Canada";
      subLocation =
        parsedLocation?.state == "USA" || parsedLocation?.state == "Canada"
          ? ""
          : parsedLocation?.state;
    }

    // Create an AbortController for this request
    const controller = new AbortController();

    dispatch(
      searchListing({
        keyword: "",
        category_id: categoryId,
        page: 1,
        user_id: CurrentUserID,
        location_longitude: lat,
        location_latitude: lon,
        location: location,
        sub_location: subLocation,
        signal: controller.signal, // Pass the signal to the thunk
      })
    );

    // Cleanup function to abort the request when dependencies change
    return () => {
      controller.abort();
    };
  }, [dispatch, CurrentUserID, categoryId, savedLocation, location]);

  useEffect(() => {
    if (searchListState?.searchList?.data?.listings) {
      setListings(searchListState?.searchList?.data?.listings);
    }
  }, [searchListState]);

  const currentCategory = categories?.data?.find(
    (item: any) => item.id === Number(categoryId)
  );

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

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

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

  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}`;
  }
  return (
    <>
      {/* large screen hero */}

      <div className="relative w-full font-system overflow-hidden">
        {/* Banner Image */}
        {categories?.data
          ?.filter((item: any) => item.id === Number(categoryId))
          .map((item: any) => (
            <div key={item.id}>
              <Image
                unoptimized
                src={item?.category_banner || heroUnion}
                alt="Category Banner"
                width={1920}
                height={500}
                className="w-full lg:h-[500px] object-cover"
              />
            </div>
          ))}

        {/* Gradient Overlay */}
        <div className="absolute top-0 w-full h-[500px] bg-gradient-to-r from-[rgba(4,16,78,0.85)] via-[rgba(4,16,78,0.39)] to-[rgba(4,16,78,1)] z-10"></div>

        {/* Text Content in Normal Flow */}
        <div className="absolute top-0 w-full h-full z-10 flex items-center">
          <div className="mx-auto max-w-7xl md:px-4 xs:px-4 w-full">
            <div className="flex flex-col gap-2 lg:gap-4 text-white w-full">
              <h1 className="text-base xs:text-sm md:text-5xl font-semibold tracking-widest">
                Buy and Sell
              </h1>
              <h2 className="text-base md:text-xl lg:text-5xl font-medium tracking-05">
                {currentCategory?.name}
              </h2>
            </div>
          </div>
        </div>
      </div>

      {/* vehicle section section */}
      <div className="font-system m-auto max-w-7xl ">
        <div className="bg-[#F8F9F9]">
          <div className=" px-4 pt-16 sm:px-6  lg:max-w-7xl  sm:mt-0 xs:pt-0">
            <div className="flex flex-col md:flex-row pb-4 justify-between items-center lg:pt-11 xs:pt-0">
              {listings?.map(
                (category: any, index: number) =>
                  index === 0 && (
                    <h1
                      key={index}
                      className="lg:text-4xl xs:mt-6 xs:mb-5 font-semibold text-[#3D3D3D] "
                    >
                      Auctions in {category.category.name}
                    </h1>
                  )
              )}
              {listings?.length > 0 && (
                <Menu as="div" className="relative inline-block text-left ">
                  <div className="border-1 rounded-sm">
                    <MenuButton className="border border-gray-300 rounded-full px-4 py-2 focus:outline-none flex justify-between text-sm font-medium text-gray-700 hover:text-gray-900 w-full gap-2 items-center">
                      <Image
                        unoptimized
                        src={Sort}
                        alt="Sort Icon"
                        width={16}
                        height={16}
                        className="group-hover:opacity-70"
                      />
                      <span className="text-gray-600 text-sm">
                        {
                          sortOptions.find((opt) => opt.value === sortType)
                            ?.name
                        }
                      </span>
                      <svg
                        className="w-4 h-4 text-gray-500 group-hover:text-gray-700"
                        xmlns="http://www.w3.org/2000/svg"
                        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>
                  </div>
                  <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-50 mt-2 w-40 origin-top-left rounded-md bg-white shadow-2xl ring-1 ring-black ring-opacity-5 focus:outline-none overflow-hidden">
                      <div className="">
                        {sortOptions.map((option) => (
                          <MenuItem key={option.value}>
                            {({ active }) => (
                              <button
                                onClick={() => handleSortChange(option.value)}
                                className={classNames(
                                  active
                                    ? "bg-navy text-white dark:bg-gray-600"
                                    : "text-gray-900 dark:text-white",
                                  "block px-4 py-2 w-full text-sm font-medium rounded-none border-b"
                                  // option.value === sortType ? "bg-gray-100" : ""
                                )}
                              >
                                {option.name}
                              </button>
                            )}
                          </MenuItem>
                        ))}
                      </div>
                    </MenuItems>
                  </Transition>
                </Menu>
              )}
            </div>
            <div
              className={`lg:mt-8 pb-6 ${
                listings?.length > 0
                  ? "grid xs:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xs:gap-3 md:gap-10"
                  : ""
              }`}
            >
              {listings?.length > 0 ? (
                listings.map((category: any) => {
                  const currentTime = DateTime.fromFormat(
                    category?.current_time_formatted,
                    "yyyy-MM-dd HH:mm:ss",
                    {
                      zone: userTimeZone,
                    }
                  );

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

                  return (
                    <div
                      key={category?.id}
                      className={`relative bg-white rounded-lg  cursor-pointer transition-transform duration-300 hover:scale-105 hover:shadow-lg overflow-hidden ${
                        isComingSoon ? "opacity-90" : ""
                      }`}
                    >
                      <div className="relative ">
                        <div className="relative xs:h-24 md:h-60 w-full overflow-hidden rounded-lg cursor-pointer">
                          {category?.images?.[0] ? (
                            <Image
                              unoptimized
                              onClick={() =>
                                handleRedirection(
                                  category.id,
                                  category.product_name,
                                  category?.category?.name
                                )
                              }
                              onMouseEnter={() => {
                                const route = getAuctionRoute(
                                  category.id,
                                  category?.category?.name || "",
                                  category.product_name
                                );
                                router.prefetch(route);
                              }}
                              src={category.images[0]}
                              alt="Product Image"
                              width={500}
                              height={300}
                              className={`h-full w-full object-cover object-center ${
                                isComingSoon
                                  ? "inset-0 bg-gradient-to-b to-transparent bg-black opacity-70"
                                  : ""
                              }`}
                            />
                          ) : (
                            <div
                              className={`h-full w-full flex items-center justify-center  bg-gray-200 text-gray-500 text-sm ${
                                isComingSoon
                                  ? "inset-0 bg-gradient-to-b to-transparent bg-black opacity-70"
                                  : ""
                              }`}
                            >
                              No Image Available
                            </div>
                          )}

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

                          <div
                            onClick={() =>
                              handleWishlistToggle(
                                category.id,
                                category.is_in_wishlist,
                                category.product_name,
                                category?.category?.name
                              )
                            }
                            onMouseEnter={() => {
                              if (!CurrentUserID) {
                                const returnUrl = getFormattedCategoryRoute(
                                  category.id,
                                  category?.category?.name || ""
                                );
                                router.prefetch(
                                  `/auth/login?callbackUrl=${encodeURIComponent(
                                    returnUrl
                                  )}`
                                );
                              }
                            }}
                            className="absolute xs:top-1 xs:left-4 md:right-2 xs:h-4 xs:w-4 md:h-6 md:w-6 bg-white rounded-full p-0 flex items-center justify-center transition-transform duration-300 hover:scale-125"
                          >
                            <Image
                              unoptimized
                              src={category.is_in_wishlist ? love : heart}
                              alt="Wishlist Icon"
                              className="xs:h-2 xs:w-2 md:h-3 md:w-3 cursor-pointer p-0"
                              width={24}
                              height={24}
                            />
                          </div>
                        </div>
                        <div>
                          {(category.bid_status === "winning" ||
                            category.bid_status === "outbid") && (
                            <button
                              className={`${
                                category.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`}
                            >
                              {category.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">
                              {!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">
                                  {category.top_bid_amount && (
                                    <div className="text-red-500 md:text-base xs:text-[0.750rem]">
                                      Current Bid :{" "}
                                      {category?.currency === "CAD"
                                        ? "C$"
                                        : category?.currency === "USD"
                                        ? "US$"
                                        : ""}{" "}
                                      {category.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.700rem]">
                                      <AuctionTimer
                                        auctionEndsAt={category.auction_ends_at}
                                        currentServerTime={
                                          category?.current_time_formatted
                                        }
                                      />
                                    </span>
                                  </div>
                                </div>
                              )}
                              <h3 className="text-lg font-bold text-gray-900 capitalize truncate">
                                {category?.product_name}
                              </h3>

                              <div className="flex justify-between mt-2">
                                <div
                                  onClick={() =>
                                    handleRedirection(
                                      category.id,
                                      category.product_name,
                                      category?.category?.name
                                    )
                                  }
                                  onMouseEnter={() => {
                                    const route = getAuctionRoute(
                                      category.id,
                                      category?.category?.name || "",
                                      category.product_name
                                    );
                                    router.prefetch(route);
                                  }}
                                  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={category.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">
                                  {category.top_bid_amount && (
                                    <div className="text-red-500 md:text-base xs:text-[0.750rem]">
                                      Current Bid :{" "}
                                      {category?.currency === "CAD"
                                        ? "C$"
                                        : category?.currency === "USD"
                                        ? "US$"
                                        : ""}{" "}
                                      {category.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.700rem]">
                                      <AuctionTimer
                                        auctionEndsAt={category.auction_ends_at}
                                        currentServerTime={
                                          category?.current_time_formatted
                                        }
                                      />
                                    </span>
                                  </div>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })
              ) : (
                <div className="flex flex-col items-center justify-center text-center md:pb-7 xs:pt-6 w-full">
                  <h2 className="md:text-4xl xs:text-xl font-semibold text-gray-700">
                    No Auction Found
                  </h2>
                </div>
              )}
            </div>
            {listings?.length > 0 && (
              <div className="flex justify-center items-center space-x-2 mt-8 pb-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="Left Arrow"
                    className="h-3 cursor-pointer"
                    width={12}
                    height={12}
                  />{" "}
                </button>

                {Array.from({ length: lastPage }, (_, index) => index + 1).map(
                  (pageNumber) => (
                    <button
                      key={pageNumber}
                      onClick={() => handlePageChange(pageNumber)}
                      className={`px-3 py-1 rounded 
                    ${
                      currentPage === pageNumber
                        ? "bg-customYellow text-gray-800"
                        : "bg-white text-gray-600"
                    }`}
                    >
                      {pageNumber}
                    </button>
                  )
                )}

                <button
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={currentPage === lastPage}
                  className="p-2 bg-gray-200 rounded disabled:opacity-50 text-black"
                >
                  <Image
                    unoptimized
                    src={rightArrow}
                    alt="Right Arrow"
                    className="h-3 cursor-pointer"
                    width={12}
                    height={12}
                  />
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default CategoryList;
