"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { useSelector } from "react-redux";
import type { RootState } from "@/state/store";
import type { DashboardOfferItem } from "@/types/dashboard";
import { KebabIcon, LensThumb, SortIcon } from "./icons";
import { getImageUrl } from "@/lib/imageUrl";
import { formatListingNo } from "@/lib/listingNo";
import ProductImage from "../common/ProductImage";

type SortKey = "id" | "product" | "offer" | "buyer" | "seller";
type SortDir = "asc" | "desc";

const COLUMNS: { key: SortKey; label: string }[] = [
  { key: "id", label: "ID" },
  { key: "product", label: "Product" },
  { key: "offer", label: "Offer" },
  { key: "buyer", label: "Buyer" },
  { key: "seller", label: "Seller" },
];

export default function RecentOffersTable() {
  const router = useRouter();
  const [openMenu, setOpenMenu] = useState<string | null>(null);
  const { offers, loading } = useSelector((state: RootState) => state.dashboard);
  const [sortKey, setSortKey] = useState<SortKey | null>(null);
  const [sortDir, setSortDir] = useState<SortDir>("asc");

  const handleSort = (key: SortKey) => {
    if (sortKey === key) {
      setSortDir((prev) => (prev === "asc" ? "desc" : "asc"));
    } else {
      setSortKey(key);
      setSortDir("asc");
    }
  };

  const sortedOffers = useMemo(() => {
    if (!sortKey) return offers;
    const list = [...offers];
    list.sort((a, b) => {
      if (sortKey === "id") {
        const aNum = a.product?.listingNo ?? 0;
        const bNum = b.product?.listingNo ?? 0;
        if (aNum !== 0 || bNum !== 0) {
          return sortDir === "asc" ? aNum - bNum : bNum - aNum;
        }
        return sortDir === "asc" ? a.id.localeCompare(b.id) : b.id.localeCompare(a.id);
      }
      if (sortKey === "product") {
        const aTitle = (a.product?.title || "").toLowerCase();
        const bTitle = (b.product?.title || "").toLowerCase();
        return sortDir === "asc" ? aTitle.localeCompare(bTitle) : bTitle.localeCompare(aTitle);
      }
      if (sortKey === "offer") {
        const aPrice = Number(a.offerPrice) || 0;
        const bPrice = Number(b.offerPrice) || 0;
        return sortDir === "asc" ? aPrice - bPrice : bPrice - aPrice;
      }
      if (sortKey === "buyer") {
        const aName = `${a.buyer?.firstName || ""} ${a.buyer?.lastName || ""}`.trim().toLowerCase();
        const bName = `${b.buyer?.firstName || ""} ${b.buyer?.lastName || ""}`.trim().toLowerCase();
        return sortDir === "asc" ? aName.localeCompare(bName) : bName.localeCompare(aName);
      }
      if (sortKey === "seller") {
        const aName = `${a.seller?.firstName || ""} ${a.seller?.lastName || ""}`.trim().toLowerCase();
        const bName = `${b.seller?.firstName || ""} ${b.seller?.lastName || ""}`.trim().toLowerCase();
        return sortDir === "asc" ? aName.localeCompare(bName) : bName.localeCompare(aName);
      }
      return 0;
    });
    return list;
  }, [offers, sortKey, sortDir]);

  return (
    <div className="min-w-0 overflow-hidden rounded-xl border border-[#E4E7EC] bg-white">
      <div className="flex items-center justify-between border-b border-[#E4E7EC] px-5 py-4">
        <h2 className="text-[16px] font-semibold text-[#101828]">Recent Offers</h2>
        <Link href="/offers" className="text-[13px] font-medium text-[#1657D9] hover:underline">
          View All
        </Link>
      </div>

      <div className="overflow-x-auto">
        {loading.offers ? (
          <div className="space-y-3 p-5">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-10 animate-pulse rounded bg-[#F2F4F7]" />
            ))}
          </div>
        ) : sortedOffers.length === 0 ? (
          <div className="p-8 text-center text-[13px] text-[#667085]">
            No recent offers available.
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#E4E7EC] bg-[#EAF1FF]">
                {COLUMNS.map(({ key, label }) => (
                  <th
                    key={key}
                    onClick={() => handleSort(key)}
                    className="cursor-pointer select-none whitespace-nowrap px-5 py-3 text-left text-[13px] font-medium text-[#475467] hover:text-[#101828]"
                  >
                    <span className="flex w-full items-center justify-between">
                      {label}
                      <SortIcon className={sortKey === key ? "text-[#1657D9]" : "opacity-60"} />
                    </span>
                  </th>
                ))}
                <th className="whitespace-nowrap px-5 py-3 text-left text-[13px] font-medium text-[#475467]">
                  Action
                </th>
              </tr>
            </thead>
            <tbody>
              {sortedOffers.map((row, index) => {
                const buyerName = row.buyer
                  ? `${row.buyer.firstName || ""} ${row.buyer.lastName || ""}`.trim() || "Unknown"
                  : "Unknown";
                const buyerEmail = row.buyer?.email || "—";
                const sellerName = row.seller
                  ? `${row.seller.firstName || ""} ${row.seller.lastName || ""}`.trim() || "Unknown"
                  : "Unknown";
                const sellerEmail = row.seller?.email || "—";
                const productTitle = row.product?.title || "Unknown Product";
                const displayId = formatListingNo(row.product?.listingNo);
                const offerPriceFormatted =
                  row.offerPrice != null
                    ? `$${Number(row.offerPrice).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
                    : "—";

                return (
                  <tr key={row.id} className="border-b border-[#F2F4F7] last:border-b-0 hover:bg-[#F9FBFF]">
                    <td className="whitespace-nowrap px-5 py-3">
                      <span className="text-[14px] font-medium text-[#1657D9]">{displayId}</span>
                    </td>
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-2.5">
                        <ProductImage
                          src={row.product?.images?.[0]}
                          alt={productTitle}
                        />
                        <span className="max-w-[200px] truncate text-[14px] text-[#344054]">{productTitle}</span>
                      </div>
                    </td>
                    <td className="whitespace-nowrap px-5 py-3 text-[14px] font-medium text-[#101828]">
                      {offerPriceFormatted}
                    </td>
                    <td className="whitespace-nowrap px-5 py-3">
                      <p className="text-[14px] text-[#101828]">{buyerName}</p>
                      <p className="text-[12px] text-[#1657D9]">{buyerEmail}</p>
                    </td>
                    <td className="whitespace-nowrap px-5 py-3">
                      <p className="text-[14px] text-[#101828]">{sellerName}</p>
                      <p className="text-[12px] text-[#1657D9]">{sellerEmail}</p>
                    </td>
                    <td className={`relative whitespace-nowrap px-5 py-3 ${openMenu === row.id ? "z-50" : ""}`}>
                      <button
                        type="button"
                        onClick={() => setOpenMenu(openMenu === row.id ? null : row.id)}
                        className="flex h-7 w-7 items-center justify-center rounded-full text-[#667085] transition-colors hover:bg-[#F2F4F7]"
                      >
                        <KebabIcon />
                      </button>
                      {openMenu === row.id && (
                        <div className={`absolute right-5 ${index >= offers.length - 2 ? "bottom-9" : "top-9"} z-50 min-w-[150px] rounded-lg border border-[#E4E7EC] bg-white py-1.5 shadow-[0_10px_24px_rgba(15,23,42,0.12)]`}>
                          <button
                            type="button"
                            onClick={() => {
                              setOpenMenu(null);
                              router.push(`/offers?id=${encodeURIComponent(row.id)}`);
                            }}
                            className="w-full whitespace-nowrap px-3.5 py-2 text-left text-[13px] text-[#344054] hover:bg-[#F5F7F9]"
                          >
                            View Details
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
