"use client";

import React, { useEffect, useState, Fragment, useMemo } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../store";
import { sellerAllOrders } from "../../../api/api";
import { formatDistanceToNow } from "date-fns";
import { Menu, Transition } from "@headlessui/react";
import { truncateDescription } from "../../../utils/commonFunction";
const sortOptions = ["Newest First", "Oldest First"];

const SellerOrder: React.FC = () => {
  const dispatch = useDispatch<any>();
  const router = useRouter();
  const [currentPage, setCurrentPage] = useState(1);
  const [sortOrder, setSortOrder] = useState("Newest First");
  const itemsPerPage = 3;

  const { data } = useSelector((state: RootState) => state.SellerOrdersReducer);

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

  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 filteredOrders = useMemo(() => {
    if (!data?.data?.orders) return [];

    const orders = [...data.data.orders];

    // Apply sort order
    orders.sort((a, b) => {
      const dateA = new Date(a.created_at).getTime();
      const dateB = new Date(b.created_at).getTime();
      return sortOrder === "Newest First" ? dateB - dateA : dateA - dateB;
    });

    return orders;
  }, [data, sortOrder]);

  const totalOrders = filteredOrders.length;
  const totalPages = Math.ceil(totalOrders / itemsPerPage);

  const paginatedOrders = useMemo(() => {
    return filteredOrders.slice(
      (currentPage - 1) * itemsPerPage,
      currentPage * itemsPerPage
    );
  }, [filteredOrders, currentPage, itemsPerPage]);

  const handleTrack = (orderId: string) => {
    router.push(`/purchaseStatus/${orderId}`);
  };

  return (
    <div className="bg-[#F8F9F9] flex flex-col w-full p-4">
      {/* Filters Section */}
      <div className="mb-6 flex   flex-row justify-between md:items-center">
        <h1 className="text-2xl font-bold text-gray-800">Sold Items</h1>

        {/* Sort Order Dropdown */}
        <Menu as="div" className="relative inline-block text-left">
          <div>
            <Menu.Button className="inline-flex justify-center w-full rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none">
              Sort: {sortOrder}
              <svg
                className="-mr-1 ml-2 h-5 w-5"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 20 20"
                fill="currentColor"
                aria-hidden="true"
              >
                <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>
            </Menu.Button>
          </div>

          <Transition
            as={Fragment}
            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"
          >
            <Menu.Items className="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none z-10 overflow-hidden">
              <div className="border-b-[1px]">
                {sortOptions.map((option) => (
                  <Menu.Item key={option}>
                    {({ active }) => (
                      <div
                        onClick={() => {
                          setSortOrder(option);
                          setCurrentPage(1);
                        }}
                        className={`${
                          active
                            ? "bg-navy text-white dark:bg-gray-600"
                            : "ext-gray-900 dark:text-white"
                        } block px-4 py-3 text-sm font-semibold cursor-pointer w-full text-left`}
                      >
                        {option}
                      </div>
                    )}
                  </Menu.Item>
                ))}
              </div>
            </Menu.Items>
          </Transition>
        </Menu>
      </div>

      {/* Orders List */}
      {paginatedOrders.length > 0 ? (
        paginatedOrders.map((values: any) => (
          <section className="relative mb-6" key={values.id}>
            <div className="flex w-full rounded-lg bg-white p-4 gap-4 cursor-pointer transition-shadow duration-300 hover:shadow-lg relative items-center">
              {/* Image with specified dimensions */}
              <div className="relative lg:w-[248px] lg:h-[200px] xs:h-[138px] xs:w-[122px] rounded-lg overflow-hidden flex-shrink-0">
                <Image
                  unoptimized
                  src={values.listing?.images[0]}
                  alt={values.listing?.product_name || "Product Image"}
                  fill
                  style={{ objectFit: "cover" }}
                  sizes="(max-width: 1024px) 122px, 248px"
                  priority={false}
                />
              </div>

              <div className="flex-1 flex flex-col min-w-0">
                <div className="flex flex-col">
                  <div className="flex justify-between">
                    <div className="min-w-0">
                      <p className="text-green-500 text-xl font-semibold flex flex-col truncate">
                        <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>
                      <h3 className="text-xl font-bold text-gray-900 mb-1 capitalize truncate">
                        {values?.listing?.product_name}
                      </h3>
                      <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>
                    </div>
                  </div>
                  <p className="hidden lg:block text-black-700 text-start lg:text-lg lg:font-semibold text-[#000000] lg:pt-1">
                    {truncateDescription(values?.listing?.description)}
                  </p>
                </div>

                <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(`/purchaseStatus/${values.id}`)
                    }
                    className="md:track-custom-button xs:track-custom-button-sm"
                  >
                    Track
                  </button>

                  {/* Status Dropdown */}
                </div>
              </div>
            </div>
          </section>
        ))
      ) : (
        <div className="bg-yellow-100 rounded-lg p-5 text-center">
          <p className="text-yellow-600 font-semibold">No Orders Found</p>
        </div>
      )}

      {/* Pagination Controls */}
      {totalPages > 1 && (
        <div className="flex justify-end mt-6 gap-4">
          <button
            onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
            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-600"
            }`}
          >
            Previous
          </button>

          <button
            onClick={() =>
              setCurrentPage((prev) => Math.min(prev + 1, totalPages))
            }
            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-600"
            }`}
          >
            Next
          </button>
        </div>
      )}
    </div>
  );
};

export default SellerOrder;
