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

export default async function PaymentFailurePage({
  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",
  });

  // تحديد نوع الفشل: إلغاء أو رفض
  const status = getParam("STATUS");
  const isDeclined = status === "2" || status === "52" || status === "declined";
  const failureType = isDeclined ? "declined" : "cancelled";

  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.error_code"),
      key: "NCERROR",
      value: getParam("NCERROR"),
    },
    {
      label: t("receipt.amount"),
      key: "amount",
      value: getParam("amount"),
    },
    {
      label: t("receipt.currency"),
      key: "currency",
      value: getParam("currency"),
    },
  ].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-[#faf7f7] to-[#f3efe6] px-6">
      <section className="w-full max-w-xl bg-white/80 backdrop-blur border border-red-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-red-50 border border-red-100">
            <span className="text-2xl">✕</span>
          </div>
          <h1 className="mt-4 text-2xl font-extrabold text-red-900">
            {t(`${failureType}.title`)}
          </h1>
          <p className="mt-2 text-sm text-slate-600 leading-6">
            {t(`${failureType}.description`)}
          </p>
        </div>

        {receiptRows.length > 0 && (
          <div className="mt-6 border border-red-100 bg-white rounded-2xl p-4">
            <div className="text-sm font-extrabold text-red-900">
              {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">
          <PaymentFailureRedirect
            gatewayPaymentId={getParam("gateway_payment_id")}
            fallbackHomeUrl={homeHref}
            fallbackDashboardUrl={dashboardHref}
            appendStatus={
              isDeclined
                ? { type: "failed_true" }
                : { type: "failed", failureType: "cancelled" }
            }
            label={t("actions.back")}
            labelReturnToPrevious={t("actions.return_to_previous")}
          />
          <Link
            href={homeHref}
            className="w-full text-center rounded-xl border border-red-200 hover:border-red-300 text-red-800 bg-white/70 px-6 py-3 font-bold transition"
          >
            {t("actions.back_home")}
          </Link>
        </div>
      </section>
    </main>
  );
}
