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

export default async function PaymentCancelledPage({
  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 t = await getTranslations({
    locale: locale || "ar",
    namespace: "PAYMENT_RESULT",
  });

  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-slate-200 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-slate-50 border border-slate-200">
            <span className="text-2xl">×</span>
          </div>
          <h1 className="mt-4 text-2xl font-extrabold text-slate-950">
            {t("cancelled.title")}
          </h1>
          <p className="mt-2 text-sm text-slate-600 leading-6">
            {t("cancelled.description")}
          </p>
        </div>

        <div className="mt-6 grid gap-3">
          <Link
            href={homeHref}
            className="w-full text-center rounded-xl bg-[#0F5132] hover:bg-[#1B7A50] text-white px-6 py-3 font-bold transition"
          >
            {t("actions.back_home")}
          </Link>
          <PaymentCancelledReturnButton
            gatewayPaymentId={getParam("gateway_payment_id")}
            fallbackHomeUrl={homeHref}
            fallbackDashboardUrl={dashboardHref}
            label={t("actions.back")}
            labelReturnToPrevious={t("actions.return_to_previous")}
          />
        </div>
      </section>
    </main>
  );
}
