import { getTranslations, setRequestLocale } from "next-intl/server";
import { Link } from "@/i18n/navigation";
import { auth } from "@/auth";
import { createMarketListingAction } from "@/app/market-actions";

export default async function NewMarketPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string }>;
  searchParams: Promise<{ error?: string }>;
}) {
  const { locale } = await params;
  const query = await searchParams;
  setRequestLocale(locale);
  const session = await auth();
  const t = await getTranslations("market");
  if (!session?.user?.id) {
    return (
      <div className="space-y-4">
        <h1 className="page-title">{t("sellTitle")}</h1>
        <p className="text-muted">{t("needLogin")}</p>
        <Link href="/login" className="btn-primary">
          {t("login")}
        </Link>
      </div>
    );
  }

  const errorKey = query.error;
  const error =
    errorKey === "details"
      ? t("err_details")
      : errorKey === "amount"
        ? t("err_amount")
        : errorKey === "photos"
          ? t("err_photos")
          : errorKey
            ? t("err_generic")
            : "";

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      <div>
        <h1 className="page-title">{t("sellTitle")}</h1>
        <p className="mt-2 text-muted">{t("sellIntro")}</p>
      </div>
      {error ? <p className="text-sm text-red-700">{error}</p> : null}
      <form action={createMarketListingAction} className="card space-y-4 p-5">
        <label className="block text-sm">
          {t("titleField")}
          <input name="title" required minLength={3} className="field mt-1" />
        </label>
        <label className="block text-sm">
          {t("details")}
          <textarea name="details" required minLength={10} rows={5} className="field mt-1" />
        </label>
        <label className="block text-sm">
          {t("specs")}
          <textarea name="specs" rows={4} className="field mt-1" />
        </label>
        <label className="block text-sm">
          {t("price")}
          <input name="priceUsdt" type="number" min={1} step="0.01" required className="field mt-1" />
        </label>
        <label className="block text-sm">
          {t("photos")}
          <input name="photos" type="file" accept="image/jpeg,image/png,image/webp" multiple required className="mt-1 w-full text-sm" />
        </label>
        <p className="text-sm text-muted">{t("noContact")}</p>
        <button className="btn-primary">{t("publish")}</button>
      </form>
    </div>
  );
}
