"use client";

import React, { Fragment, useEffect, useState } from "react";
import {
  Menu,
  Transition,
  MenuItem,
  MenuItems,
  MenuButton,
} from "@headlessui/react";
import { ChevronDownIcon } from "@heroicons/react/20/solid";
import Image from "next/image";
import { truncateDescription } from "../../utils/commonFunction";
import { HiDotsVertical } from "react-icons/hi";
import { postDraft } from "../../api/api";
import Chip from "../../common/Chip";
import { formatDate } from "../../common/DateFormant";
import CommonPopup from "../../common/CommonPopup";
import Swal from "sweetalert2";
import { toast } from "react-toastify";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { RootState } from "../../store";
function classNames(...classes: any) {
  return classes.filter(Boolean).join(" ");
}
interface SellerResultsProps {
  listData: any[];
  onDelete: (id: any) => void;
  onRefresh: () => void;
}

const SellerResults: React.FC<SellerResultsProps> = ({
  listData,
  onDelete,
  onRefresh,
}) => {
  const router = useRouter();
  const [sortOrder, setSortOrder] = useState("Newest");
  const [currentPage, setCurrentPage] = useState(1);
  const [isOpen, setIsOpen] = useState(false);
  const itemsPerPage = 3;
  const [showPopup, setShowPopup] = useState(false);
  const [selectedId, setSelectedId] = useState<any>(null);
  const { incrementData } = useSelector(
    (state: RootState) => state.MessageCountReducer
  );
  const AuctionSellerFee = incrementData?.data?.auctionFee[0]?.seller_fee;
  useEffect(() => {
    const routesToPrefetch = ["/profile/seller/listing"];

    routesToPrefetch.forEach((route) => {
      router.prefetch(route);
    });
  }, [router]);

  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);
  };

  const handlePostDraft = async (data: any) => {
    const payload = {
      draft_id: data,
    };

    const result = await Swal.fire({
      text: `This action will deduct $${AuctionSellerFee} from your wallet`,
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "Confirm",
      cancelButtonText: "Decline",
      confirmButtonColor: "#d33",
      cancelButtonColor: "#3085d6",
    });

    if (result.isConfirmed) {
      try {
        const response = await postDraft(payload);
        console.log(response);
        onRefresh();
        router.push(`/profile/seller/listing`);
      } catch (error: any) {
        toast.error(error?.response?.data?.error);
      }
    } else {
      console.log("User cancelled the action.");
    }
  };

  const handleDeleteListing = (id: any) => {
    setSelectedId(id);
    setShowPopup(true);
  };

  const handleConfirmDelete = () => {
    if (selectedId !== null) {
      onDelete(selectedId);
    }
    setShowPopup(false);
    setSelectedId(null);
  };

  const handleCancelDelete = () => {
    setShowPopup(false);
    setSelectedId(null);
  };

  const handleEditListing = (listingId: number) => {
    router.push(`/ad-details?id=${listingId}`);
  };

  const handleTrackListing = (listingId: number) => {
    router.push(`/purchaseStatus/${listingId}`);
  };

  const sortOptions = [
    { name: "Newest first", value: "Newest" },
    { name: "Oldest first", value: "Oldest" },
  ];

  const sortedListings =
    sortOrder === "Oldest" ? [...listData].reverse() : listData;

  // Apply pagination after sorting
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentListings = sortedListings.slice(
    indexOfFirstItem,
    indexOfLastItem
  );

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

  return (
    <div className="bg-[#F8F9F9] flex flex-col w-full space-y-4 mb-4">
      <section className="flex xs:flex-row xs:justify-around flex-col space-y-2 items-center md:justify-between rounded-lg">
        <span className="text-black font-semibold">
          Results - {listData.length} Listings
        </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 px-4 py-2">
              <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 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 }) => (
                      <div
                        onClick={() => setSortOrder(option.value)}
                        className={classNames(
                          active
                            ? "bg-navy text-white dark:bg-gray-600"
                            : "text-gray-900 dark:text-white",
                          "block px-4 py-3 text-sm font-medium w-full border-b"
                        )}
                      >
                        {option.name}
                      </div>
                    )}
                  </MenuItem>
                ))}
              </div>
            </MenuItems>
          </Transition>
        </Menu>
      </section>

      {currentListings.length > 0 ? (
        currentListings.map((listing: any) =>
          listing.approved_status === 1 ? (
            <section className="relative md:px-0 xs:p-3" key={listing.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">
                <div className="relative my-2 mx-2 lg:w-[348px] border lg:h-[190px] xs:h-[138px] xs:w-[221px] rounded-xl p-2">
                  <Image
                    unoptimized
                    src={listing.images[0]}
                    alt="Listing"
                    fill
                    className="object-cover rounded-lg"
                  />
                </div>
                <div className="bg-white rounded-b lg:rounded-b-none lg:rounded-r p-1 flex flex-col md:flex-row justify-between leading-normal w-full">
                  <div className="flex justify-between relative">
                    <div>
                      <p className="text-green-500 sm:text-2xl font-semibold text-start xs:text-sm">
                        {listing?.currency === "USD" ? "US$" : "C$"}{" "}
                        {/* {listing?.converted_price} */}
                        {listing?.top_bid && listing.top_bid > 0
                          ? listing.top_bid
                          : listing?.product_type === "Unreserved"
                          ? listing?.starting_bid ?? 0
                          : listing?.reserve_price ?? 0}
                      </p>
                      <div className="xs:text-sm sm:text-2xl text-gray-900 font-bold lg:text-3xl mb-1 text-start lg:pt-1 capitalize">
                        {listing.product_name}
                      </div>
                      <div className="lg:text-lg text-gray-600 lg:pt-1">
                        <p className="flex items-center gap-1 xs:text-sm sm:text-xl font-medium">
                          <span>{formatDate(listing?.created_at)}</span> |
                          <span>{listing.location}</span>
                        </p>
                      </div>
                      <p className="hidden lg:block lg:text-lg lg:font-semibold text-start text-black lg:pt-1 whitespace-pre-wrap break-words break-all ">
                        {truncateDescription(listing.description)}
                      </p>
                      <div className="flex gap-2">
                        {listing?.is_draft === 0 && (
                          <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 xs:w-[8.29rem]  mt-2"
                          >
                            <span className="relative z-10 xs:text-xs p-0 font-semibold md:text-[0.900rem] cursor-pointer">
                              VIEW
                            </span>
                          </div>
                        )}
                        {listing?.listing_status === "completed" && (
                          <div
                            onClick={() =>
                              router.push(`/orderStatus/${listing?.order?.id}`)
                            }
                            onMouseEnter={() =>
                              router.prefetch(
                                `/orderStatus/${listing?.order?.id}`
                              )
                            }
                            className="md:custom-button-price xs:custom-button-sm xs:w-[8.29rem] mt-2"
                          >
                            <span className="relative z-10 xs:text-xs p-0 font-semibold md:text-[0.900rem] cursor-pointer">
                              TRACK
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                    <div className="absolute right-[2px] top-0 md:hidden">
                      <Menu
                        as="div"
                        className="relative inline-block text-left focus:outline-none ring-0"
                      >
                        <Menu.Button
                          className="flex items-center gap-2 cursor-pointer px-0  focus:outline-none ring-0"
                          onClick={() => setIsOpen(!isOpen)}
                        >
                          <HiDotsVertical className="w-6 h-6 text-black" />
                        </Menu.Button>
                        <Transition
                          as={Fragment}
                          enter="transition ease-out duration-200"
                          enterFrom="opacity-0 translate-y-2"
                          enterTo="opacity-100 translate-y-0"
                          leave="transition ease-in duration-150"
                          leaveFrom="opacity-100 translate-y-0"
                          leaveTo="opacity-0 translate-y-2"
                        >
                          <Menu.Items className="absolute z-50 right-3 w-56 origin-top-right bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none rounded-md overflow-hidden">
                            {!!listing?.is_draft && (
                              <div className="border-b-[1px]">
                                <Menu.Item>
                                  {({ active }) => (
                                    <div
                                      className={`${
                                        active
                                          ? "bg-navy text-white dark:bg-gray-600"
                                          : "text-gray-900 dark:text-white"
                                      } group items-center px-4 py-2 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                      onClick={() =>
                                        handlePostDraft(listing?.id)
                                      }
                                    >
                                      Post Your Draft
                                    </div>
                                  )}
                                </Menu.Item>
                              </div>
                            )}

                            {listing?.listing_status != "completed" && (
                              <div className="border-b-[1px]">
                                <Menu.Item>
                                  {({ active }) => (
                                    <div
                                      className={`${
                                        active
                                          ? "bg-navy text-white dark:bg-gray-600"
                                          : "text-gray-900 dark:text-white"
                                      } group items-center px-4 py-2 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                      onClick={() =>
                                        handleEditListing(listing.id)
                                      }
                                      onMouseEnter={() =>
                                        router.prefetch(
                                          `/ad-details?id=${listing.id}`
                                        )
                                      }
                                    >
                                      Edit
                                    </div>
                                  )}
                                </Menu.Item>
                              </div>
                            )}
                            {listing?.listing_status == "completed" && (
                              <div className="border-b-[1px]">
                                <Menu.Item>
                                  {({ active }) => (
                                    <div
                                      className={`${
                                        active
                                          ? "bg-navy text-white dark:bg-gray-600"
                                          : "text-gray-900 dark:text-white"
                                      } group items-center px-4 py-2 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                      onClick={() =>
                                        handleTrackListing(listing.id)
                                      }
                                      onMouseEnter={() =>
                                        router.prefetch(
                                          `/purchaseStatus/${listing.id}`
                                        )
                                      }
                                    >
                                      Track
                                    </div>
                                  )}
                                </Menu.Item>
                              </div>
                            )}

                            <div className="border-b-[1px]">
                              <Menu.Item>
                                {({ active }) => (
                                  <div
                                    className={`${
                                      active
                                        ? "bg-navy text-white dark:bg-gray-600"
                                        : "text-gray-900 dark:text-white"
                                    } group items-center px-4 py-2 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none `}
                                    onClick={() =>
                                      handleDeleteListing(listing.id)
                                    }
                                  >
                                    Delete
                                  </div>
                                )}
                              </Menu.Item>
                            </div>
                          </Menu.Items>
                        </Transition>
                      </Menu>
                    </div>
                  </div>
                  <div className="lg:right-4 flex flex-col xs:right-6 xs:bottom-4 md:top-6">
                    <div className="flex">
                      <div className="pt-2">
                        <Chip text={listing?.listing_status} />
                      </div>

                      <div className="hidden md:block">
                        <Menu
                          as="div"
                          className="relative inline-block text-left "
                        >
                          <Menu.Button
                            className="flex items-center gap-2 cursor-pointer text-black"
                            onClick={() => setIsOpen(!isOpen)}
                          >
                            <HiDotsVertical className="w-6 h-6 text-black" />
                          </Menu.Button>
                          <Transition
                            as={Fragment}
                            enter="transition ease-out duration-200"
                            enterFrom="opacity-0 translate-y-2"
                            enterTo="opacity-100 translate-y-0"
                            leave="transition ease-in duration-150"
                            leaveFrom="opacity-100 translate-y-0"
                            leaveTo="opacity-0 translate-y-2"
                          >
                            <Menu.Items className="absolute z-40 right-3 w-56 origin-top-right bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none rounded-md overflow-hidden">
                              {!!listing?.is_draft && (
                                <div className="border-b-[1px] ">
                                  <Menu.Item>
                                    {({ active }) => (
                                      <div
                                        className={`${
                                          active
                                            ? "bg-navy text-white dark:bg-gray-600"
                                            : "text-gray-900 dark:text-white"
                                        } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                        onClick={() =>
                                          handlePostDraft(listing?.id)
                                        }
                                      >
                                        Post Your Draft
                                      </div>
                                    )}
                                  </Menu.Item>
                                </div>
                              )}
                              {listing?.listing_status != "completed" && (
                                <div className="border-b-[1px] ">
                                  <Menu.Item>
                                    {({ active }) => (
                                      <div
                                        className={`${
                                          active
                                            ? "bg-navy text-white dark:bg-gray-600"
                                            : "text-gray-900 dark:text-white"
                                        } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                        onClick={() =>
                                          handleEditListing(listing.id)
                                        }
                                        onMouseEnter={() =>
                                          router.prefetch(
                                            `/ad-details?id=${listing.id}`
                                          )
                                        }
                                      >
                                        Edit
                                      </div>
                                    )}
                                  </Menu.Item>
                                </div>
                              )}
                              {listing?.listing_status == "completed" && (
                                <div className="border-b-[1px] ">
                                  <Menu.Item>
                                    {({ active }) => (
                                      <div
                                        className={`${
                                          active
                                            ? "bg-navy text-white dark:bg-gray-600"
                                            : "text-gray-900 dark:text-white"
                                        } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none`}
                                        onClick={() =>
                                          handleTrackListing(listing.id)
                                        }
                                        onMouseEnter={() =>
                                          router.prefetch(
                                            `/purchaseStatus/${listing.id}`
                                          )
                                        }
                                      >
                                        Track
                                      </div>
                                    )}
                                  </Menu.Item>
                                </div>
                              )}
                              <div className="border-b-[1px] ">
                                <Menu.Item>
                                  {({ active }) => (
                                    <div
                                      className={`${
                                        active
                                          ? "bg-navy text-white dark:bg-gray-600"
                                          : "text-gray-900 dark:text-white"
                                      } group items-center px-4 py-3 text-sm font-semibold flex justify-between cursor-pointer w-full rounded-none `}
                                      onClick={() =>
                                        handleDeleteListing(listing.id)
                                      }
                                    >
                                      Delete
                                    </div>
                                  )}
                                </Menu.Item>
                              </div>
                            </Menu.Items>
                          </Transition>
                        </Menu>
                      </div>
                    </div>
                    <div>
                      {listing?.can_repost === true && (
                        <button
                          onClick={() =>
                            router.push(`/repostDetail?id=${listing.id}`)
                          }
                          className="rounded-lg py-[6px] w-[8rem] items-center font-sans text-xs font-bold leading-none text-white bg-yellow-500 mt-2"
                        >
                          Repost
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              </div>
              {showPopup && (
                <CommonPopup
                  title="Delete Listing"
                  description="Are you sure you want to permanently delete ?"
                  confirmText="Yes"
                  cancelText="No"
                  onConfirm={handleConfirmDelete}
                  onCancel={handleCancelDelete}
                  showCancel={true}
                  showConfirm={true}
                />
              )}
            </section>
          ) : null
        )
      ) : (
        <p className="text-center text-black">No listings found</p>
      )}

      <div className="flex justify-end items-center mt-4 gap-6 p-3">
        <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-700"
          }`}
        >
          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-700"
          }`}
        >
          Next
        </button>
      </div>
    </div>
  );
};

export default SellerResults;
