import { getTranslations, setRequestLocale } from "next-intl/server";
import { Link } from "@/i18n/navigation";
import { notFound } from "next/navigation";
import { auth } from "@/auth";
import { buyMarketListingAction, closeMarketListingAction } from "@/app/market-actions";
import { ShopGallery } from "@/components/shop-gallery";
import { getEscrowSettings } from "@/lib/escrow";
import { getListing } from "@/lib/market";

export default async function MarketItemPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string; id: string }>;
  searchParams: Promise<{ error?: string }>;
}) {
  const { locale, id } = await params;
  const query = await searchParams;
  setRequestLocale(locale);
  const listing = await getListing(id);
  if (!listing) notFound();
  const t = await getTranslations("market");
  const session = await auth();
  const settings = await getEscrowSettings();
  const isSeller = session?.user?.id === listing.sellerId;
  const canBuy = Boolean(session?.user?.id) && !isSeller && listing.status === "ACTIVE";
  const fee = Math.round(listing.priceUsdt * (settings.feePercent / 100) * 1_000_000) / 1_000_000;
  const sellerGets = Math.round((listing.priceUsdt - fee) * 1_000_000) / 1_000_000;
  const error =
    query.error === "policy"
      ? t("err_policy")
      : query.error === "self"
        ? t("err_self")
        : query.error === "sold"
          ? t("err_sold")
          : query.error === "user_not_found"
            ? t("err_generic")
            : query.error
              ? t("err_generic")
              : "";

  return (
    <div className="space-y-6">
      <Link href="/market" className="text-sm text-brand">
        {t("back")}
      </Link>
      <div className="grid grid-cols-1 items-start gap-8 lg:grid-cols-2">
        <ShopGallery photos={listing.photos} alt={listing.title} aspect="4/3" />
        <div className="min-w-0 space-y-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-gold">{t("viaEscrow")}</p>
          <h1 className="page-title">{listing.title}</h1>
          <p className="text-2xl font-bold text-brand">{listing.priceUsdt} USDT</p>
          <p className="text-sm text-muted">
            {t("seller")}: {listing.sellerName}
          </p>
          <p className="whitespace-pre-wrap leading-7">{listing.details}</p>
          {listing.specs ? (
            <div className="rounded-2xl bg-background p-4">
              <h2 className="font-semibold">{t("specs")}</h2>
              <p className="mt-2 whitespace-pre-wrap text-sm leading-7 text-muted">{listing.specs}</p>
            </div>
          ) : null}
          <p className="text-sm text-muted">{t("feeLine", { percent: settings.feePercent, fee, seller: sellerGets })}</p>
          <p className="text-sm text-muted">{t("noContact")}</p>
          {error ? <p className="text-sm text-red-700">{error}</p> : null}
          {listing.status !== "ACTIVE" ? (
            <p className="rounded-xl bg-background px-4 py-3 text-sm">{t(`st_${listing.status}`)}</p>
          ) : null}
          {isSeller && listing.status !== "SOLD" && listing.status !== "CLOSED" ? (
            <form action={closeMarketListingAction}>
              <input type="hidden" name="id" value={listing.id} />
              <button className="btn-ghost">{t("close")}</button>
            </form>
          ) : null}
          {canBuy ? (
            <form action={buyMarketListingAction} className="card space-y-3 p-5">
              <input type="hidden" name="id" value={listing.id} />
              <label className="flex items-start gap-2 text-sm">
                <input name="acceptPolicy" type="checkbox" required className="mt-1" />
                <span>{t("accept")}</span>
              </label>
              <button className="btn-primary w-full">{t("buy")}</button>
            </form>
          ) : null}
          {!session?.user?.id ? (
            <Link href="/login" className="btn-primary inline-flex">
              {t("loginToBuy")}
            </Link>
          ) : null}
        </div>
      </div>
    </div>
  );
}
