import Link from "next/link";
import { LotCard } from "@/components/cards";
import { PageShell } from "@/components/page";
import { prisma } from "@/lib/prisma";
import { AUCTION_CATEGORIES, isWholesale } from "@/lib/roles";
import { readSession } from "@/lib/session";

const STATUS_TABS = [
  { value: "", label: "All" },
  { value: "live", label: "Live" },
  { value: "scheduled", label: "Upcoming" },
  { value: "closed", label: "Closed" },
] as const;

const STATUS_ORDER: Record<string, number> = { live: 0, scheduled: 1, closed: 2 };

function hrefFor(status: string, category: string) {
  const params = new URLSearchParams();
  if (status) params.set("status", status);
  if (category) params.set("category", category);
  const query = params.toString();
  return query ? `/auctions?${query}` : "/auctions";
}

export default async function AuctionsPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; category?: string }>;
}) {
  const { status = "", category = "" } = await searchParams;
  const session = await readSession();
  const now = new Date();
  await prisma.auction.updateMany({
    where: { endsAt: { lt: now }, status: { not: "closed" } },
    data: { status: "closed" },
  });
  await prisma.auction.updateMany({
    where: { startsAt: { lte: now }, endsAt: { gt: now }, status: "scheduled" },
    data: { status: "live" },
  });

  const auctions = await prisma.auction.findMany({
    include: { _count: { select: { bids: true } } },
  });

  const visible = auctions.filter((auction) => {
    if (auction.wholesaleOnly && !isWholesale(session)) return false;
    return true;
  });

  const activeStatus = STATUS_TABS.some((tab) => tab.value === status) ? status : "";
  const activeCategory = AUCTION_CATEGORIES.some((item) => item.value === category) ? category : "";

  const filtered = visible
    .filter((auction) => (activeStatus ? auction.status === activeStatus : true))
    .filter((auction) => (activeCategory ? auction.category === activeCategory : true))
    .sort((a, b) => {
      const rank = (STATUS_ORDER[a.status] ?? 9) - (STATUS_ORDER[b.status] ?? 9);
      return rank || a.endsAt.getTime() - b.endsAt.getTime();
    });

  const statusCounts = Object.fromEntries(
    STATUS_TABS.map((tab) => [
      tab.value || "all",
      visible.filter((auction) => (!tab.value || auction.status === tab.value) && (!activeCategory || auction.category === activeCategory)).length,
    ]),
  );

  return (
    <PageShell
      wide
      eyebrow="Auctions"
      title="Lots on the clock"
      lede="Staff-selected stones. Members bid against the timer. Wholesale lots stay behind the trade door."
    >
      <div className="dir-toolbar">
        <nav className="floor-tabs dir-tabs" aria-label="Filter by clock">
          {STATUS_TABS.map((tab) => (
            <Link
              key={tab.value || "all"}
              href={hrefFor(tab.value, activeCategory)}
              className={activeStatus === tab.value ? "is-on" : undefined}
            >
              {tab.label}
              <small>{statusCounts[tab.value || "all"]}</small>
            </Link>
          ))}
        </nav>
        <nav className="floor-tabs dir-tabs auction-cats" aria-label="Filter by grade">
          <Link href={hrefFor(activeStatus, "")} className={activeCategory === "" ? "is-on" : undefined}>
            Every grade
          </Link>
          {AUCTION_CATEGORIES.map((item) => (
            <Link
              key={item.value}
              href={hrefFor(activeStatus, item.value)}
              className={activeCategory === item.value ? "is-on" : undefined}
            >
              {item.label}
            </Link>
          ))}
        </nav>
      </div>

      <div className="dir-count">
        <h2>{activeStatus === "live" ? "Live now" : activeStatus === "scheduled" ? "Upcoming" : activeStatus === "closed" ? "Closed" : "This week’s lots"}</h2>
        <p>
          {filtered.length} {filtered.length === 1 ? "lot" : "lots"}
        </p>
      </div>

      {filtered.length === 0 ? (
        <p className="dir-empty">No lots in this column.</p>
      ) : (
        <div className="lot-grid auction-list">
          {filtered.map((auction) => (
            <LotCard
              key={auction.id}
              href={`/auctions/${auction.id}`}
              title={auction.title}
              imageUrl={auction.imageUrl}
              origin={auction.origin}
              category={
                AUCTION_CATEGORIES.find((item) => item.value === auction.category)?.label ||
                auction.category
              }
              status={auction.status}
              currentBid={auction.currentBid}
              endsAt={auction.endsAt.toISOString()}
              bidCount={auction._count.bids}
              wholesale={auction.wholesaleOnly}
            />
          ))}
        </div>
      )}
    </PageShell>
  );
}
