import { getTranslations, setRequestLocale } from "next-intl/server";
import { Link } from "@/i18n/navigation";
import { auth } from "@/auth";
import { listMarket, listMyMarket } from "@/lib/market";

export default async function MarketPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  setRequestLocale(locale);
  const t = await getTranslations("market");
  const session = await auth();
  const [listings, mine] = await Promise.all([
    listMarket(),
    session?.user?.id ? listMyMarket(session.user.id) : Promise.resolve([]),
  ]);

  return (
    <div className="space-y-8">
      <section className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <h1 className="page-title">{t("title")}</h1>
          <p className="mt-2 max-w-2xl text-muted">{t("intro")}</p>
        </div>
        <Link href="/market/new" className="btn-primary shrink-0">
          {t("sellCta")}
        </Link>
      </section>
      {session && mine.length > 0 ? (
        <p className="text-sm text-muted">
          {t("myCount", { n: mine.length })}
        </p>
      ) : null}
      {listings.length === 0 ? <p className="text-muted">{t("empty")}</p> : null}
      <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
        {listings.map((item) => (
          <Link key={item.id} href={`/market/${item.id}`} className="card card-interactive overflow-hidden">
            {item.photos[0] ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={`/api/media/${item.photos[0]}`} alt={item.title} className="aspect-[4/3] w-full object-cover" />
            ) : (
              <div className="aspect-[4/3] bg-background" />
            )}
            <div className="p-4">
              <h2 className="font-semibold">{item.title}</h2>
              <p className="mt-1 text-brand font-bold">{item.priceUsdt} USDT</p>
              <p className="mt-1 text-xs text-muted">
                {t("seller")}: {item.sellerName}
                {item.status === "RESERVED" ? ` · ${t("reserved")}` : ""}
              </p>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
