"use client";

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { toast } from "react-toastify";
import { DateTime } from "luxon";
import { RootState } from "../../../store";
import { fetchAllWishlist, DeleteWishlist } from "../../../api/api";
import { truncateDescription } from "../../../utils/commonFunction";
import love from "../../../assets/loveHeart1.png";
import TimeAgo from "../../../common/TimeAgo";
import AuctionTimer from "../../../components/bayerProfile/pages/components/AuctionTimer";
import TimerIcon from "../../../assets/TimeIcon.png";

const Wishlist: React.FC = () => {
  const dispatch = useDispatch<any>();
  const router = useRouter();

  const [currentPage, setCurrentPage] = useState(1);
  const [likedProducts, setLikedProducts] = useState<{
    [key: string]: boolean;
  }>({});
  const itemsPerPage = 3;

  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const userTimeZone = homedata?.data?.settings?.default_timezone || "UTC";

  const data = useSelector((state: RootState) => state.AllWishlistReducer);
  const wishlistData = data?.data?.data?.wishlists || [];
  console.log("wishlistData", wishlistData);
  useEffect(() => {
    dispatch(fetchAllWishlist());
  }, [dispatch]);

  const toggleLike = async (productId: string) => {
    const isCurrentlyLiked = likedProducts[productId] || false;
    setLikedProducts((prev) => ({ ...prev, [productId]: !isCurrentlyLiked }));

    try {
      await dispatch(DeleteWishlist(productId)).unwrap();
      toast.success("Removed from wishlist!");
      dispatch(fetchAllWishlist());
    } catch (error) {
      console.error(error);
      setLikedProducts((prev) => ({ ...prev, [productId]: isCurrentlyLiked }));
      toast.error(
        `Error ${!isCurrentlyLiked ? "adding to" : "removing from"} wishlist.`
      );
    }
  };

  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = wishlistData.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(wishlistData.length / itemsPerPage);

  const handleNextPage = () => {
    if (currentPage < totalPages) setCurrentPage((prev) => prev + 1);
  };

  const handlePrevPage = () => {
    if (currentPage > 1) setCurrentPage((prev) => prev - 1);
  };

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

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

  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 (
    <div className="font-system">
      <div className="mx-auto px-4 sm:px-6 lg:max-w-7xl lg:px-8">
        <div className="flex justify-between items-center">
          <h2 className="md:text-4xl xs:text-2xl font-bold text-gray-900 xs:mb-4 md:mb-0">
            Wishlist Product
          </h2>
        </div>

        <div>
          {currentItems.length > 0 ? (
            currentItems.map((wishlist: any) => {
              const currentTime = DateTime.now().setZone(userTimeZone);
              const startTime = DateTime.fromISO(
                wishlist?.listing?.start_datetime?.replace(" ", "T") || "",
                {
                  zone: userTimeZone,
                }
              );
              const isComingSoon = startTime > currentTime;

              return (
                <section className="relative xs:mt-3 xs:mb-5" key={wishlist.id}>
                  <div className="flex w-full rounded-lg bg-white sm:m-auto sm:mb-4 lg:p-3 lg:gap-3 md:gap-5 cursor-pointer transition-transform duration-300 hover:scale-105 hover:shadow-lg">
                    {/* Image with overlay */}
                    <div className="relative xs:h-[137px] xs:w-[200px] lg:h-[210px] lg:min-w-72">
                      {wishlist?.listing?.images?.[0] && (
                        <Image
                          unoptimized
                          src={wishlist.listing.images[0]}
                          alt="Wishlist"
                          fill
                          className="object-cover rounded-2xl"
                          style={{ objectPosition: "center" }}
                        />
                      )}

                      {/* Coming Soon Overlay */}
                      {isComingSoon && (
                        <div className="absolute inset-0 bg-black/60 rounded-2xl flex flex-col items-center justify-center text-center text-white px-2 py-3">
                          <span className="text-xs md:text-sm xs:text-xs font-semibold uppercase tracking-widest animate-pulse">
                            COMING SOON
                          </span>
                          <p className="text-[0.65rem] md:text-sm xs:text-xs opacity-90">
                            Stay tuned! Items will be
                          </p>
                          <p className="text-[0.65rem] md:text-sm xs:text-xs opacity-90 mb-1">
                            available soon.
                          </p>
                          <span className="text-[0.65rem] md:text-sm opacity-80">
                            {formatStartDateTime(
                              wishlist?.listing?.start_datetime
                            )}
                          </span>
                        </div>
                      )}
                    </div>

                    {/* Right Section (Details) */}
                    <div className="bg-white rounded-b lg:rounded-b-none lg:rounded-r p-1 flex justify-between leading-normal w-full relative">
                      <div className="w-full">
                        <div className="xs:text-xl text-gray-900 font-bold lg:text-xl mb-1 text-start lg:pt-1 capitalize text-wrap w-10/12">
                          {wishlist.listing?.product_name}
                        </div>
                        <div className="mb-3 lg:mb-1 lg:pt-1">
                          <p className="flex items-center gap-1 font-medium">
                            <span className="xs:text-sm lg:text-lg text-gray-600">
                              <TimeAgo
                                timestamp={wishlist?.listing?.created_at}
                              />
                            </span>
                            {" | "}
                            <span className="xs:text-sm lg:text-lg text-gray-600">
                              {wishlist.listing.location}
                            </span>
                          </p>
                        </div>
                        <p className="hidden text-black-700 text-start lg:text-lg lg:font-semibold text-[#000000] md:block lg:pt-1 capitalize">
                          {truncateDescription(wishlist.listing.description)}
                        </p>
                        <div className="flex items-center xs:gap-1 md:gap-0 md:justify-between pt-3">
                          <div
                            onClick={() =>
                              handleRedirection(
                                wishlist.listing_id,
                                wishlist?.listing?.category?.name || "",
                                wishlist.listing?.product_name
                              )
                            }
                            onMouseEnter={() => {
                              const route = getAuctionRoute(
                                wishlist.listing_id,
                                wishlist?.listing?.category?.name || "",
                                wishlist.listing?.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>
                          {/* <p className="hidden lg:block font-bold xs:text-xs md:text-lg text-gray-500">
                            <TimeAgo
                              timestamp={wishlist?.listing?.created_at}
                            />
                          </p> */}
                          <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 text-red-500 xs:text-[0.750rem]">
                              <AuctionTimer
                                // auctionStartsAt={
                                //   product?.start_datetime
                                // }
                                auctionEndsAt={
                                  wishlist?.listing?.auction_ends_at
                                }
                                currentServerTime={
                                  wishlist?.current_time_formatted
                                }
                              />
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Like (heart) icon */}
                      <div
                        onClick={() => toggleLike(wishlist.listing.id)}
                        className="absolute lg:right-4 xs:right-2 lg:top-4 md:right-6 h-6 w-6 bg-gray-100 rounded-full p-0 flex items-center justify-center"
                      >
                        <Image
                          unoptimized
                          src={love}
                          alt="Heart"
                          width={12}
                          height={12}
                          className="cursor-pointer"
                        />
                      </div>
                    </div>
                  </div>
                </section>
              );
            })
          ) : (
            <div className="bg-yellow-100 lg:mt-20 rounded-lg p-5 mb-7">
              <p className="text-yellow-600 flex justify-center font-semibold">
                No Results found
              </p>
            </div>
          )}
        </div>

        {wishlistData.length > 0 && (
          <div className="flex justify-end mt-5 mb-6 gap-6">
            <button
              onClick={handlePrevPage}
              disabled={currentPage === 1}
              className={`px-4 py-2 rounded text-white ${
                currentPage === 1
                  ? "bg-gray-300 cursor-not-allowed"
                  : "bg-yellow-500 hover:bg-yellow-700"
              }`}
            >
              Previous
            </button>
            <button
              onClick={handleNextPage}
              disabled={currentPage === totalPages}
              className={`px-4 py-2 rounded text-white ${
                currentPage === totalPages
                  ? "bg-gray-300 cursor-not-allowed"
                  : "bg-yellow-500 hover:bg-yellow-700"
              }`}
            >
              Next
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default Wishlist;
