/* commented to resolve build errors */
"use client";

import React, { useState, useEffect } from "react";
import Sort from "../../assets/Sort.png";
import {
  Menu,
  Transition,
  MenuItem,
  MenuItems,
  MenuButton,
} from "@headlessui/react";
import Image from "next/image";
import { RootState } from "../../store";
import { useSelector } from "react-redux";
import { formatDate } from "../../common/DateFormant";
import data from "../../assets/Data.png";
import Filter from "../../components/bayerProfile/pages/components/MainFilterContainer";
import { truncateDescription } from "../../utils/commonFunction";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { DateTime } from "luxon";
import TimeAgo from "../../common/TimeAgo";

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

const SearchList = () => {
  // const dispatch: AppDispatch = useDispatch();
  const searchListState = useSelector(
    (state: RootState) => state.searchReducer
  );
  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const userTimeZone = homedata?.data?.settings.default_timezone || "UTC";
  const router = useRouter();
  const searchParams = useSearchParams();
  const keyword = searchParams.get("keyword") || "";
  const [searchListingData, setSearchListingData] = useState<any>([]);
  const searchListingsData = searchListState?.searchList?.data?.listings;
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(3);
  const [sortType, setSortType] = useState("Most recent");

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

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

  const sortListings = (order: string) => {
    const sortedListings = [...searchListingData].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;
    });
    setSearchListingData(sortedListings);
  };

  useEffect(() => {
    if (searchListingsData) {
      setSearchListingData(searchListingsData);
    }
  }, [searchListingsData]);

  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = searchListingData.slice(
    indexOfFirstItem,
    indexOfLastItem
  );

  const handleNextPage = () => {
    if (currentPage < Math.ceil(searchListingData.length / itemsPerPage)) {
      setCurrentPage(currentPage + 1);
    }
  };

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

  // Helper function to build URL
  const getAuctionUrl = (
    id: number,
    categoryName?: string,
    productName?: string
  ) => {
    const formattedCategoryName = (
      categoryName?.replace(/[^a-zA-Z0-9\s]/g, "").replace(/\s+/g, "-") ||
      "default-category"
    ).toLowerCase();

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

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

  const handleRedirection = (
    id: number,
    categoryName?: string,
    productName?: string
  ) => {
    const url = getAuctionUrl(id, categoryName, productName);
    router.push(url);
  };

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

    const [datePart, timePartRaw] = datetimeStr.split(" ");

    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>
      <div className="container max-w-7xl m-auto p-0">
        <div className="text-start text-lg pt-8 xs:hidden">
          <div className="list-none p-0 inline-flex">
            <Link href="/" className="text-[#878787]">
              Home
            </Link>
            <span className="mx-2 text-[#878787]">{">"}</span>
            <p className="lg:text-md text-[#878787]">Search list</p>
          </div>
        </div>

        <div className="pt-6">
          <h2 className="lg:text-3xl xs:text-xl md:text-3xl font-bold text-[#3D3D3D] md:text-start px-4">
            Result found with {keyword}
          </h2>
        </div>

        <div>
          <div className="grid grid-cols-1 md:grid-cols-1 lg:grid-cols-12 lg:pt-9">
            <div className="col-span-1 md:col-span-4 flex flex-col">
              <Filter />
            </div>

            <div className="col-span-1 md:col-span-6 lg:col-span-8 md:p-4 xs:p-2">
              <div className="md:flex justify-around flex items-center lg:flex lg:items-center mb:text-center md:justify-between mb-2">
                <p className="text-black font-semibold text-sm md:text-base">
                  Results - {searchListingData.length} Listings
                </p>

                {searchListingData.length > 1 && (
                  <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"
                          className="w-4 h-4 group-hover:opacity-80"
                          width={16}
                          height={16}
                        />
                        <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={() =>
                                    handleSortChangeData(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="mt-5">
                {currentItems.length > 0 ? (
                  currentItems.map((listing: any, index: number) => {
                    const currentTime = DateTime.fromFormat(
                      listing?.current_time_formatted,
                      "yyyy-MM-dd HH:mm:ss",
                      {
                        zone: userTimeZone,
                      }
                    );

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

                    return (
                      <div
                        key={index}
                        className="relative flex max-w-sm w-full md:max-w-full md:flex lg:max-w-full lg:flex mb-4 mt-3 rounded-lg bg-white sm:m-auto sm:mb-4 sm:max-w-[28rem] lg:p-3 lg:gap-3 md:gap-2 cursor-pointer transition-transform duration-300 hover:scale-105 hover:shadow-lg"
                      >
                        <div className="relative">
                          {listing.images?.[0] ? (
                            <Image
                              unoptimized
                              src={listing.images[0]}
                              alt={listing.product_name}
                              width={300}
                              height={200}
                              className={`md:min-w-56 object-cover md:h-[201px] xs:h-[126px] xs:min-w-[122px] lg:p-0 md:rounded-2xl h-auto xs:rounded-xl ${
                                isComingSoon
                                  ? "inset-0 bg-black opacity-70"
                                  : ""
                              }`}
                            />
                          ) : (
                            <div className="md:min-w-56 md:h-[201px] xs:h-[126px] xs:min-w-[122px] flex items-center justify-center bg-gray-200 text-gray-500 text-sm md:rounded-2xl xs:rounded-xl">
                              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 md:p-4 bg-black opacity-70 md:rounded-2xl xs:rounded-xl">
                              <span className="md:text-[1.25rem] xs:text-sm leading-[2rem] font-bold uppercase animate-pulse tracking-widest">
                                Coming Soon
                              </span>
                              <p className="md:text-base xs:text-sm opacity-80">
                                Stay tuned! Items will be available soon.
                              </p>
                              <span className="md:text-base xs:text-sm opacity-80">
                                {formatStartDateTime(listing?.start_datetime)}
                              </span>
                            </div>
                          )}
                        </div>

                        <div className="bg-white rounded-b lg:rounded-b-none lg:rounded-r p-1 flex flex-col justify-between leading-normal w-full">
                          <div>
                            <div className="xs:text-lg text-gray-900 font-bold lg:text-2xl mb-1 text-start lg:pt-1">
                              {listing.product_name}
                            </div>

                            <div className="lg:text-lg xs:text-sm mb-3 lg:mb-1 text-gray-600 lg:pt-1">
                              <p className="flex items-center gap-1 xs:text-sm sm:text-lg font-medium text-gray-600">
                                <span>{formatDate(listing?.created_at)}</span> |{" "}
                                <span>{listing?.location}</span>
                              </p>
                            </div>

                            <p className="hidden text-black-700 text-start lg:text-md font-semibold text-[#000000] md:block lg:pt-1">
                              {truncateDescription(listing.description)}
                            </p>

                            <div className="flex md:justify-between items-center mt-2 xs:gap-2">
                              <div
                                onClick={() =>
                                  handleRedirection(
                                    listing.id,
                                    listing?.category?.name,
                                    listing.product_name
                                  )
                                }
                                onMouseEnter={() => {
                                  const url = getAuctionUrl(
                                    listing.id,
                                    listing?.category?.name,
                                    listing.product_name
                                  );
                                  router.prefetch(url);
                                }}
                                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>
                                  <TimeAgo timestamp={listing.created_at} />
                                </p>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })
                ) : (
                  <div className="flex justify-center flex-col items-center">
                    <p className="text-black text-xl font-bold text-center">
                      We couldn&apos;t find what you&apos;re looking for.
                      <br />
                      Check your query, change your keywords, or adjust your
                      filter settings.
                    </p>
                    <Image
                      unoptimized
                      src={data}
                      alt="Preview"
                      width={256}
                      height={256}
                      className="h-64 w-64"
                    />
                  </div>
                )}
              </div>

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

export default SearchList;
