import Link from "next/link";
import { cookies } from "next/headers";
import { getTranslations } from "next-intl/server";
import PaymentSuccessReturnButton from "@/components/payment/PaymentSuccessReturnButton";

export default async function PaymentSuccessPage({
  searchParams,
}: {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
}) {
  const sp = searchParams ? await searchParams : undefined;

  const getParam = (key: string) => {
    const v = sp?.[key];
    return Array.isArray(v) ? v[0] : v;
  };

  const cookieStore = await cookies();
  const cookieLocale =
    cookieStore.get("NEXT_LOCALE")?.value ||
    cookieStore.get("locale")?.value ||
    undefined;

  const qpLocaleRaw = sp?.lang;
  const qpLocale = Array.isArray(qpLocaleRaw) ? qpLocaleRaw[0] : qpLocaleRaw;

  const locale = qpLocale || cookieLocale;
  const homeHref = locale ? `/${locale}` : "/";
  const dashboardHref = locale ? `/${locale}/dashboard` : "/";
  const isAr = (locale || "ar").startsWith("ar");

  const t = await getTranslations({
    locale: locale || "ar",
    namespace: "PAYMENT_RESULT",
  });

  const receiptRows: Array<{ label: string; key: string; value?: string }> = [
    {
      label: t("receipt.order_ref"),
      key: "OrderRef",
      value: getParam("OrderRef"),
    },
    {
      label: t("receipt.pay_id"),
      key: "PAYID",
      value: getParam("PAYID"),
    },
    {
      label: t("receipt.status"),
      key: "STATUS",
      value: getParam("STATUS"),
    },
    {
      label: t("receipt.amount"),
      key: "amount",
      value: getParam("amount"),
    },
    {
      label: t("receipt.currency"),
      key: "currency",
      value: getParam("currency"),
    },
    {
      label: t("receipt.brand"),
      key: "BRAND",
      value: getParam("BRAND"),
    },
    {
      label: t("receipt.payment_method"),
      key: "PM",
      value: getParam("PM"),
    },
    {
      label: t("receipt.card_holder"),
      key: "CN",
      value: getParam("CN"),
    },
    {
      label: t("receipt.error_code"),
      key: "NCERROR",
      value: getParam("NCERROR"),
    },
    {
      label: t("receipt.acceptance"),
      key: "ACCEPTANCE",
      value: getParam("ACCEPTANCE"),
    },
  ].filter((r) => r.value !== undefined && String(r.value).trim() !== "");

  return (
    <main className="min-h-screen flex items-center justify-center bg-gradient-to-br from-[#faf7f0] via-[#f7faf9] to-[#f3efe6] px-6">
      <section className="w-full max-w-xl bg-white/80 backdrop-blur border border-emerald-100 rounded-2xl shadow-lg p-8">
        <div className="text-center">
          <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-emerald-50 border border-emerald-100">
            <span className="text-2xl">✓</span>
          </div>
          <h1 className="mt-4 text-2xl font-extrabold text-emerald-950">
            {t("success.title")}
          </h1>
          <p className="mt-2 text-sm text-slate-600 leading-6">
            {t("success.description")}
          </p>
        </div>

        {receiptRows.length > 0 && (
          <div className="mt-6 border border-emerald-100 bg-white rounded-2xl p-4">
            <div className="text-sm font-extrabold text-emerald-950">
              {t("receipt.title")}
            </div>
            <div className="mt-3 divide-y">
              {receiptRows.map((row) => (
                <div
                  key={row.key}
                  className="py-2 flex items-center justify-between gap-4 text-sm"
                >
                  <span className="text-slate-600">{row.label}</span>
                  <span className="font-bold text-slate-900 text-right break-all select-text">
                    {row.value}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="mt-6 grid gap-3">
          {/* Manual next step only: no auto-redirect off this page. */}
          <PaymentSuccessReturnButton
            gatewayPaymentId={getParam("gateway_payment_id")}
            fallbackHomeUrl={homeHref}
            fallbackDashboardUrl={dashboardHref}
            labelContinue={t("actions.continue")}
            labelReturnToPrevious={t("actions.return_to_previous")}
          />
          <Link
            href={homeHref}
            className="w-full text-center rounded-xl border border-emerald-200 hover:border-emerald-300 text-emerald-800 bg-white/70 px-6 py-3 font-bold transition"
          >
            {t("actions.back_home")}
          </Link>
        </div>
      </section>
    </main>
  );
}
