"use client";

import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import {
  Menu,
  Transition,
  MenuItem,
  MenuItems,
  MenuButton,
} from "@headlessui/react";
import { ChevronDownIcon } from "@heroicons/react/20/solid";
import { RootState } from "../../store";
import { allOrders, trackOrder } from "../../api/api";
// import OrderStatus from "../../components/bayerProfile/pages/components/Tracking";
import { formatDistanceToNow } from "date-fns";
import { truncateDescription } from "../../utils/commonFunction";
import Image from "next/image";
import OrderStatus from "../orderStatus/[id]/page";
import { useRouter } from "next/navigation";

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

const Results: React.FC = () => {
  const dispatch = useDispatch<any>();
  const [selectedOrderId, setSelectedOrderId] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(5); // Number of items per page
  const [sortOrder, setSortOrder] = useState("Newest");
  const router = useRouter();

  const sortOptions = [
    { name: "Newest first", value: "Newest" },
    { name: "Oldest first", value: "Oldest" },
  ];
  const { data } = useSelector((state: RootState) => state.OrdersReducer);
  const { orderData } = useSelector(
    (state: RootState) => state.OrderTrackReducer
  );
  const ordersData = data?.data?.orders;

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

  const handleTrack = (orderId: string) => {
    setSelectedOrderId(orderId);
    dispatch(trackOrder(orderId));
    router.push(`/orderStatus/${orderId}`);
  };

  const getTimeAgo = (timestamp: any) => {
    let timeAgo = formatDistanceToNow(new Date(timestamp), { addSuffix: true });
    timeAgo = timeAgo.replace("about ", "");
    return timeAgo;
  };
  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}`;
  };
  const handleRedirection = (
    id: number,
    categoryName: string,
    productName: string
  ) => {
    const route = getFormattedRoute(id, categoryName, productName);
    router.push(route);
  };

  const handleSort = (order: string) => {
    setSortOrder(order);
  };

  const sortedOrders = [...(ordersData || [])].sort((a: any, b: any) => {
    if (sortOrder === "Newest") {
      return (
        new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
      );
    } else {
      return (
        new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
      );
    }
  });

  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentOrders = sortedOrders.slice(indexOfFirstItem, indexOfLastItem);

  const totalPages = Math.ceil((ordersData?.length || 0) / itemsPerPage);

  return (
    <div className="bg-[#F8F9F9] flex flex-col font-system py-5 w-full space-y-4">
      <section className="flex flex-row space-y-2 items-center justify-around md:justify-between rounded-lg">
        <span className="text-black font-semibold">
          Results - {ordersData.length}
        </span>
        <Menu as="div" className="relative inline-block text-left">
          <div className="border-2 rounded-md">
            <MenuButton className="group flex justify-between text-sm font-medium text-gray-700 hover:text-gray-900 w-full">
              <span>Sort By : {sortOrder} </span>
              <ChevronDownIcon
                className="-mr-1 ml-1 h-5 w-5 flex-shrink-0 text-gray-400 group-hover:text-gray-500"
                aria-hidden="true"
              />
            </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 left-0 z-10 mt-2 w-40 origin-top-left divide-y divide-gray-200 rounded-md bg-white shadow-2xl ring-1 ring-black ring-opacity-5 focus:outline-none overflow-hidden">
              <div className="">
                {sortOptions.map((option: any) => (
                  <MenuItem key={option.name}>
                    {({ active }) => (
                      <div
                        onClick={() => handleSort(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  border-b"
                        )}
                      >
                        {option.name}
                      </div>
                    )}
                  </MenuItem>
                ))}
              </div>
            </MenuItems>
          </Transition>
        </Menu>
      </section>

      {selectedOrderId && orderData ? (
        <div>
          <OrderStatus />
        </div>
      ) : (
        currentOrders.map((values: any) => (
          <section className=" md:px-0 xs:p-4 " key={values.id}>
            <div className="flex max-w-sm w-full md:max-w-full md:flex lg:max-w-full lg:flex md:mb-4 lmd:mt-3 relative rounded-lg bg-white sm:m-auto sm:mb-4 sm:max-w-[28rem] lg:p-3 lg:gap-3 md:gap-5 cursor-pointer transition-transform duration-300 hover:scale-105 hover:shadow-lg">
              <Image
                unoptimized
                className="lg:w-[248px] lg:h-[212px] xs:h-[114px] xs:w-[122px] lg:p-0 rounded-lg p-2 object-cover"
                src={values.listing?.images[0]}
                alt="image"
                height={212}
                width={248}
              />

              <div className=" bg-white rounded-b lg:rounded-b-none lg:rounded-r p-1 flex justify-between leading-normal ">
                <div>
                  <p className="text-green-500 md:text-2xl font-semibold text-start xs:text-lg flex flex-col">
                    <span>
                      {values?.currency === "USD" ? "US$" : "C$"}{" "}
                      {values?.converted_price}
                    </span>
                    {values?.listing?.currency != values?.currency && (
                      <span className="text-gray-500 font-semibold text-base">
                        {values?.listing?.currency === "USD" ? "US$" : "C$"}{" "}
                        {values?.bid_amount}
                      </span>
                    )}
                  </p>
                  <div className="xs:text-lg  text-gray-900 font-bold lg:text-3xl mb-1 text-start lg:pt-1 capitalize">
                    {values?.listing?.product_name}
                  </div>

                  <p className="flex items-center gap-1 text-base font-medium text-gray-600 mb-2">
                    <span>{getTimeAgo(values?.created_at)}</span> |{" "}
                    <span>{values.listing.location}</span>
                  </p>
                  <p className="hidden text-black-700 text-start lg:text-lg lg:font-semibold text-[#000000] lg:block lg:pt-1">
                    {truncateDescription(values.listing?.description)}
                  </p>
                  <div className="flex gap-2 mt-2">
                    <button
                      onClick={() =>
                        handleRedirection(
                          values?.listing?.id,
                          values?.listing?.product_name,
                          values?.listing?.category?.name
                        )
                      }
                      onMouseEnter={() => {
                        const route = getFormattedRoute(
                          values?.id,
                          values?.listing?.category?.name,
                          values?.listing?.product_name
                        );
                        router.prefetch(route);
                      }}
                      className="bg-yellow-500 hover:bg-yellow-600 text-black font-bold md:py-2 md:px-3 xs:p-2 rounded-xs text-sm"
                    >
                      View
                    </button>
                    <button
                      onClick={() => handleTrack(values.id)}
                      onMouseEnter={() =>
                        router.prefetch(`/orderStatus/${values.id}`)
                      }
                      className="md:track-custom-button xs:track-custom-button-sm"
                    >
                      Track
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </section>
        ))
      )}

      {/* Pagination */}
      <div className="flex justify-end gap-4 xs:p-4 md:p-0">
        <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={() => setCurrentPage((prev) => prev - 1)}
          disabled={currentPage === 1}
        >
          Previous
        </button>
        <button
          className={`px-4 py-2 rounded text-white ${
            currentPage === totalPages
              ? "bg-gray-300 cursor-not-allowed"
              : "bg-yellow-500 hover:bg-yellow-700"
          }`}
          onClick={() => setCurrentPage((prev) => prev + 1)}
          disabled={currentPage === totalPages}
        >
          Next
        </button>
      </div>
    </div>
  );
};

export default Results;
