"use client";

import { useState, useMemo, useEffect } from "react";

function getIsIOS(): boolean {
  if (typeof navigator === "undefined") return false;
  const ua = navigator.userAgent;
  const platform = navigator.platform ?? "";
  const maxTouchPoints = navigator.maxTouchPoints ?? 0;
  const isIPadUA = /iPad/.test(ua);
  const isIPhoneOrIPod = /iPhone|iPod/.test(ua);
  const isIPadStandalone =
    platform === "MacIntel" && maxTouchPoints > 1 && !(window as any).MSStream;
  const result = isIPadUA || isIPhoneOrIPod || isIPadStandalone;
  if (process.env.NODE_ENV === "development") {
    console.log("[TopUpModal] iOS check", {
      userAgent: ua,
      platform,
      maxTouchPoints,
      isIPadUA,
      isIPhoneOrIPod,
      isIPadStandalone,
      isIOS: result,
    });
  }
  return result;
}
import {
  Button,
  Spinner,
  Input,
  Image,
  DatePicker,
  Select,
  SelectItem,
} from "@heroui/react";
import { useTranslations, useLocale } from "next-intl";
import axios from "axios";
import { useSession } from "@/auth/session-provider";
import { BaseModal } from "@/components/modal";
import { uploadImage } from "@/actions/upload-image";
import { useQueryClient } from "@tanstack/react-query";
import { useAppToast } from "@/app/[lang]/providers";
import {
  buildWalletTopUpInvoiceHtml,
  coerceWalletTopUpInvoiceInputFromResponse,
  openInvoiceWindow,
} from "@/lib/invoice";
import { payWithGateway } from "@/actions/payment";
import {
  buildReturnPathForGatewayRequest,
  persistGatewayMetaFromGatewayResponse,
} from "@/lib/payment-return";
import { useApplePayVisible } from "@/lib/platform";
import PaymentGatewayModal from "@/components/payment/PaymentGatewayModal";
import { API_BASE_URL } from "@/lib/axios";
import { parseMoneyValue, toMoneyNumber } from "@/lib/moneyParse";

const API_URL = API_BASE_URL;

type PaymentPurpose = {
  id: string;
  key: "bank_transfer" | "online_payment" | string;
  name: string;
  status: boolean;
  media_files?: { logo?: { id: number | null; url: string } };
};

type BankItem = {
  id: string;
  name: string;
  account_holder_name?: string;
  account_number?: string;
  iban?: string;
  unique_id?: any;
  media_files?: { logo?: { id: number | null; url: string } };
};

interface TopUpModalProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  defaultAmount?: number | string;
  onSuccess?: (data: any) => void;
}

export default function TopUpModal({
  isOpen,
  onOpenChange,
  defaultAmount,
  onSuccess,
}: TopUpModalProps) {
  const t = useTranslations("DASHBOARD.WALLET-REQUEST");
  const lang = useLocale();
  const session = useSession();
  const queryClient = useQueryClient();
  const toast = useAppToast();

  const applePayVisible = useApplePayVisible();
  const [creating, setCreating] = useState(false);
  const [amount, setAmount] = useState("");
  const [methods, setMethods] = useState<PaymentPurpose[]>([]);
  const [selectedMethod, setSelectedMethod] = useState<PaymentPurpose | null>(
    null,
  );
  const [banksLoading, setBanksLoading] = useState(false);
  const [banks, setBanks] = useState<BankItem[]>([]);
  const [selectedBankId, setSelectedBankId] = useState<string | null>(null);
  const isBankTransfer = selectedMethod?.key === "bank_transfer";
  const [topUpDate, setTopUpDate] = useState<any>(null);
  const [uploadingProof, setUploadingProof] = useState(false);
  const [proof, setProof] = useState<{
    collection_name: string;
    url: string;
  } | null>(null);
  const [isProofPreviewOpen, setIsProofPreviewOpen] = useState(false);
  const [successState, setSuccessState] = useState<{
    invoiceHtml?: string;
  } | null>(null);
  const [gatewayUrl, setGatewayUrl] = useState<string | null>(null);
  const [showGatewayModal, setShowGatewayModal] = useState(false);
  const [showValidation, setShowValidation] = useState(false);
  const [isIOS, setIsIOS] = useState(false);

  useEffect(() => {
    const value = getIsIOS();
    setIsIOS(value);
  }, []);

  const resetState = () => {
    setAmount("");
    setSelectedMethod(null);
    setBanks([]);
    setSelectedBankId(null);
    setTopUpDate(null);
    setProof(null);
    setSuccessState(null);
    setShowValidation(false);
  };

  // Convert Arabic/Hindi numerals to English
  const toEnglishDigits = (str: string): string => {
    const arabicNumerals = "٠١٢٣٤٥٦٧٨٩";
    const hindiNumerals = "۰۱۲۳۴۵۶۷۸۹";
    let result = str;
    for (let i = 0; i < 10; i++) {
      result = result.replace(new RegExp(arabicNumerals[i], "g"), String(i));
      result = result.replace(new RegExp(hindiNumerals[i], "g"), String(i));
    }
    return result;
  };

  const selectedBank = useMemo(
    () => banks.find((b) => String(b.id) === String(selectedBankId)),
    [banks, selectedBankId],
  );

  const openInit = async () => {
    try {
      const token = session?.access_token;
      const res = await axios.get(
        `${API_URL}/user/dashboard/payment-purposes`,
        {
          params: { payment_purpose: "wallet_top_up" },
          headers: {
            Authorization: token ? `Bearer ${token}` : "",
            Accept: "application/json",
            lang,
          },
        },
      );
      const allMethods: PaymentPurpose[] = res.data?.data || [];
      const filtered = allMethods.filter(
        (m) => m.key !== "apple_pay" || applePayVisible,
      );
      setMethods(filtered);
    } catch (e) {
      setMethods([]);
    }
  };

  useEffect(() => {
    if (isOpen) {
      openInit();
      if (defaultAmount !== undefined && defaultAmount !== null) {
        const n = parseMoneyValue(defaultAmount);
        if (n !== undefined && n > 0) {
          setAmount(String(n));
        }
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, defaultAmount]);

  // Re-fetch/filter methods if Apple Pay visibility resolved after the modal opened
  useEffect(() => {
    if (isOpen && applePayVisible) {
      openInit();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [applePayVisible]);

  const loadBanks = async () => {
    setBanksLoading(true);
    try {
      const token = session?.access_token;
      const res = await axios.get(`${API_URL}/user/dashboard/banks`, {
        headers: {
          Authorization: token ? `Bearer ${token}` : "",
          Accept: "application/json",
          lang,
        },
      });
      setBanks(res.data?.data || []);
    } catch (e) {
      setBanks([]);
    } finally {
      setBanksLoading(false);
    }
  };

  const onSelectMethod = async (m: PaymentPurpose) => {
    setSelectedMethod(m);
    if (m.key === "bank_transfer") await loadBanks();
  };

  const canSubmit = useMemo(() => {
    const amt = toMoneyNumber(amount, 0);
    if (!amt || amt <= 0) return false;
    if (!selectedMethod) return false;
    if (isBankTransfer && !selectedBankId) return false;
    if (isBankTransfer && !topUpDate) return false;
    if (isBankTransfer && uploadingProof) return false;
    if (isBankTransfer && !proof?.url) return false;
    return true;
  }, [
    amount,
    selectedMethod,
    isBankTransfer,
    selectedBankId,
    topUpDate,
    uploadingProof,
    proof?.url,
  ]);

  const isGatewayPayment =
    selectedMethod?.key === "online_payment" ||
    selectedMethod?.key === "apple_pay";

  const submitCreate = async () => {
    setShowValidation(true);
    if (!canSubmit) {
      toast.error(
        t("fill_required_fields", {
          defaultValue: "يرجى تعبئة جميع الحقول المطلوبة",
        }),
      );
      return;
    }
    setCreating(true);
    try {
      // Online Payment: use payWithGateway action
      if (isGatewayPayment) {
        const returnPath = buildReturnPathForGatewayRequest() ?? "/";
        const gatewayRes = await payWithGateway({
          payment_purpose: "wallet_top_up",
          amount: toMoneyNumber(amount, 0),
          payment_method:
            selectedMethod?.key === "apple_pay" ? "apple_pay" : "online_payment",
          return_path: returnPath,
        });

        const receivedGatewayUrl =
          (gatewayRes as any)?.data?.payment_url ||
          (gatewayRes as any)?.data?.redirect_url;

        if ((gatewayRes as any)?.success && receivedGatewayUrl) {
          persistGatewayMetaFromGatewayResponse(
            (gatewayRes as any)?.data as Record<string, unknown>,
            returnPath,
          );
          toast.info(
            t("redirecting_to_gateway", {
              defaultValue: "جاري تحويلك إلى بوابة الدفع...",
            }),
          );
          setGatewayUrl(receivedGatewayUrl);
          setShowGatewayModal(true);
        } else {
          // Show error if gateway call failed
          console.error("Gateway payment failed:", gatewayRes?.message);
          toast.error(
            (gatewayRes as any)?.message ||
            t("gateway_error", {
              defaultValue: "حدث خطأ أثناء الاتصال ببوابة الدفع",
            }),
          );
        }
        return;
      }

      // Bank Transfer: existing flow
      const token = session?.access_token;
      const payload: any = {
        amount: toMoneyNumber(amount, 0),
        payment_method: selectedMethod?.key,
        methodable_id: isBankTransfer ? selectedBankId : selectedMethod?.id,
      };
      if (topUpDate) {
        const d = topUpDate instanceof Date ? topUpDate : new Date(topUpDate);
        payload.top_up_date = d.toISOString().split("T")[0];
      } else if (isBankTransfer) {
        payload.top_up_date = new Date().toISOString().split("T")[0];
      }
      if (proof?.url)
        payload.media_files = [
          { collection_name: proof.collection_name, url: proof.url },
        ];

      const res = await axios.post(
        `${API_URL}/user/dashboard/wallet-top-up-requests`,
        payload,
        {
          headers: {
            Authorization: token ? `Bearer ${token}` : "",
            Accept: "application/json",
            "Content-Type": "application/json",
            lang,
          },
        },
      );

      onSuccess?.(res.data);

      const data = res.data?.data;
      if (data?.checkout_url) {
        window.open(data.checkout_url, "_blank");
        await queryClient.invalidateQueries({ queryKey: ["wallet_requests"] });
        await queryClient.invalidateQueries({ queryKey: ["wallet-balances"] });
        resetState();
        onOpenChange(false);
        return;
      } else {
        // Generate invoice for bank transfer; show success with explicit "View invoice".
        const invoiceInput = coerceWalletTopUpInvoiceInputFromResponse({
          topUpResponse: res.data,
          fallback: {
            clientName: "—",
            clientMobile: "—",
            topUpAmount: toMoneyNumber(amount, 0),
            paymentMethod: isBankTransfer
              ? "Bank Transfer - تحويل بنكي"
              : "Online Payment - دفع إلكتروني",
            transactionStatus: "Pending - قيد المراجعة",
          },
        });
        const invoiceHtml = buildWalletTopUpInvoiceHtml(invoiceInput);
        setSuccessState({ invoiceHtml });
      }
      await queryClient.invalidateQueries({ queryKey: ["wallet_requests"] });
      await queryClient.invalidateQueries({ queryKey: ["wallet-balances"] });
    } catch (e: any) {
      console.error("TopUp error:", e);
      const errData = e?.response?.data;
      const message =
        errData?.message ||
        (Array.isArray(errData?.errors)
          ? Object.values(errData.errors).flat().join(" ")
          : errData?.error) ||
        e?.message ||
        t("submit_error", { defaultValue: "حدث خطأ أثناء إرسال الطلب" });
      toast.error(message);
    } finally {
      setCreating(false);
    }
  };

  const isRtl = lang === "ar";

  return (
    <BaseModal
      isOpen={isOpen}
      onOpenChange={(open) => {
        onOpenChange(open);
        if (!open) resetState();
        if (open) openInit();
      }}
      title={t("top_up_wallet", { defaultValue: "شحن المحفظة" })}
      contentClassName="max-w-2xl"
      bodyClassName="p-0"
    >
      <div
        dir={isRtl ? "rtl" : "ltr"}
        className="flex flex-col max-h-[70vh] sm:max-h-[75vh]"
      >
        {successState ? (
          <div className="p-6 text-center space-y-5">
            <div className="rounded-2xl bg-emerald-50 border border-emerald-200 p-4">
              <p className="text-sm text-emerald-800 leading-relaxed">
                {t("success_message", {
                  defaultValue:
                    "تم إرسال طلب شحن المحفظة بنجاح. يمكنك عرض الفاتورة إذا رغبت.",
                })}
              </p>
            </div>
            <Button
              color="primary"
              className="min-w-[120px]"
              onPress={() => {
                resetState();
                onOpenChange(false);
              }}
            >
              {t("close", { defaultValue: "إغلاق" })}
            </Button>
          </div>
        ) : (
          <>
            <div className="flex-1 overflow-y-auto px-6 py-4 space-y-6">
              {/* الخطوة 1: المبلغ */}
              <section className="space-y-3">
                <h3 className="text-sm font-bold text-slate-700 border-slate-200 pb-1">
                  {t("amount")} <span className="text-red-500">*</span>
                </h3>
                <Input
                  type="number"
                  label={t("amount")}
                  placeholder={lang === "ar" ? "أدخل المبلغ" : "Enter amount"}
                  value={amount}
                  onChange={(e) => {
                    const englishValue = toEnglishDigits(e.target.value);
                    setAmount(englishValue);
                  }}
                  min={"1"}
                  isRequired
                  isInvalid={
                    showValidation &&
                      (!amount || toMoneyNumber(amount, 0) <= 0)
                  }
                  errorMessage={
                    showValidation &&
                      (!amount || toMoneyNumber(amount, 0) <= 0)
                      ? t("amount_required", { defaultValue: "المبلغ مطلوب" })
                      : undefined
                  }
                  classNames={{ inputWrapper: "rounded-xl border-slate-200" }}
                />
              </section>

              {/* الخطوة 2: طريقة الدفع */}
            <section className="space-y-3">
              <h3 className="text-sm font-bold text-slate-700 pb-1">
                {t("choose_payment_method", {
                  defaultValue: "اختر طريقة الدفع",
                })}{" "}
                <span className="text-red-500">*</span>
              </h3>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                {methods.length === 0 && (
                  <div className="col-span-2 py-6 flex items-center justify-center gap-2 text-slate-500 text-sm rounded-xl bg-slate-50">
                    <Spinner size="sm" />
                    {t("loading", { defaultValue: "جاري التحميل..." })}
                  </div>
                )}
                {methods.map((m) => (
                  <button
                    key={m.id}
                    type="button"
                    onClick={() => onSelectMethod(m)}
                    className={`flex items-center gap-3 p-4 rounded-xl border-2 text-start transition min-h-[72px] ${selectedMethod?.id === m.id
                      ? "border-[#0F5132] bg-emerald-50/50 ring-2 ring-[#0F5132]/20"
                      : showValidation && !selectedMethod
                        ? "border-red-300 bg-red-50/30"
                        : "border-slate-200 bg-white hover:border-slate-300 hover:bg-slate-50/50"
                      }`}
                  >
                    {m.media_files?.logo?.url && (
                      <Image
                        alt=""
                        src={m.media_files.logo.url}
                        width={40}
                        height={40}
                        className="rounded-lg object-contain shrink-0"
                      />
                    )}
                    <div className="min-w-0 text-start">
                      <div className="font-semibold text-slate-800 truncate">
                        {m.key === "bank_transfer"
                          ? t("bank_transfer")
                          : m.key === "online_payment"
                            ? t("online_payment", {
                                defaultValue: "دفع إلكتروني",
                              })
                            : m.key === "apple_pay"
                              ? "Apple Pay"
                              : m.name}
                      </div>
                      {/* <div className="text-xs text-slate-500 mt-0.5">
                          {m.key === "online_payment" && isIOS
                            ? lang === "ar"
                              ? "ابل باي · Apple Pay"
                              : "Apple Pay"
                            : m.name}
                        </div> */}
                    </div>
                  </button>
                ))}
              </div>
              {showValidation && !selectedMethod && methods.length > 0 && (
                <p className="text-sm text-red-600 mt-1">
                  {t("payment_method_required", {
                    defaultValue: "طريقة الدفع مطلوبة",
                  })}
                </p>
              )}
            </section>

            {/* الخطوة 3: التحويل البنكي (إن وجد) */}
            {isBankTransfer && (
              <section className="space-y-4 rounded-2xl border border-slate-200 bg-slate-50/50 p-4">
                <h3 className="text-sm font-bold text-slate-700">
                  {t("select_bank", { defaultValue: "اختر البنك" })}{" "}
                  <span className="text-red-500">*</span>
                </h3>
                {banksLoading ? (
                  <div className="py-8 flex justify-center rounded-xl bg-white">
                    <Spinner size="sm" />
                  </div>
                ) : (
                  <Select
                    aria-label="bank"
                    selectedKeys={selectedBankId ? [selectedBankId] : []}
                    onChange={(e) => setSelectedBankId(e.target.value)}
                    placeholder={t("select_bank", {
                      defaultValue: "اختر البنك",
                    })}
                    isRequired
                    isInvalid={showValidation && !selectedBankId}
                    errorMessage={
                      showValidation && !selectedBankId
                        ? t("bank_required", {
                          defaultValue: "اختيار البنك مطلوب",
                        })
                        : undefined
                    }
                    classNames={{
                      trigger: "rounded-xl border-slate-200 bg-white",
                    }}
                  >
                    {banks.map((b) => (
                      <SelectItem key={b.id} textValue={b.name}>
                        <div className="flex items-center gap-2">
                          {b.media_files?.logo?.url && (
                            <Image
                              alt=""
                              src={b.media_files.logo.url}
                              width={24}
                              height={24}
                              className="rounded object-contain"
                            />
                          )}
                          <span className="font-medium">{b.name}</span>
                        </div>
                      </SelectItem>
                    ))}
                  </Select>
                )}

                <div className="pt-2">
                  <DatePicker
                    label={t("top_up_date", { defaultValue: "تاريخ الشحن" })}
                    value={topUpDate}
                    onChange={(v) => setTopUpDate(v as any)}
                    isRequired
                    isInvalid={showValidation && !topUpDate}
                    className="w-full"
                  />
                </div>

                {selectedBank && (
                  <div className="rounded-xl bg-white border border-slate-200 p-4 space-y-4">
                    <div className="flex items-center gap-3">
                      {selectedBank.media_files?.logo?.url && (
                        <Image
                          alt=""
                          src={selectedBank.media_files.logo.url}
                          width={40}
                          height={40}
                          className="rounded-lg object-contain shrink-0"
                        />
                      )}
                      <div>
                        <div className="text-sm font-bold text-slate-800">
                          {selectedBank.name}
                        </div>
                        {selectedBank.unique_id && (
                          <div className="text-xs text-slate-500 mt-0.5">
                            {t("bank_unique_id", {
                              defaultValue: "رمز البنك",
                            })}
                            :{" "}
                            <span className="font-mono">
                              {selectedBank.unique_id}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                      <div>
                        <div className="text-xs text-slate-500 mb-1">
                          {t("account_holder_name", {
                            defaultValue: "اسم صاحب الحساب",
                          })}
                        </div>
                        <div className="px-3 py-2 rounded-lg bg-slate-50 border border-slate-100 text-slate-800">
                          {selectedBank.account_holder_name || "—"}
                        </div>
                      </div>
                      <div>
                        <div className="text-xs text-slate-500 mb-1">
                          {t("account_number", {
                            defaultValue: "رقم الحساب",
                          })}
                        </div>
                        <div className="px-3 py-2 rounded-lg bg-slate-50 border border-slate-100 font-mono text-xs break-all">
                          {selectedBank.account_number || "—"}
                        </div>
                      </div>
                      <div className="sm:col-span-2">
                        <div className="text-xs text-slate-500 mb-1">
                          {t("iban", { defaultValue: "رقم الآيبان" })}
                        </div>
                        <div className="px-3 py-2 rounded-lg bg-slate-50 border border-slate-100 font-mono text-xs break-all">
                          {selectedBank.iban || "—"}
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                <div className="space-y-2">
                  <h4 className="text-sm font-bold text-slate-700">
                    {t("payment_proof", { defaultValue: "إيصال التحويل" })}{" "}
                    <span className="text-red-500">*</span>
                  </h4>
                  <Input
                    type="file"
                    accept="image/*,.pdf"
                    onChange={async (e) => {
                      const file = e.target.files?.[0];
                      if (!file) return;
                      setUploadingProof(true);
                      try {
                        const fd = new FormData();
                        fd.append("model_name", "WalletTopUpRequest");
                        fd.append("media[payment_proof]", file);
                        const res = await uploadImage(fd);
                        const uploaded = Array.isArray(res?.data)
                          ? res.data[0]
                          : null;
                        if (uploaded?.url)
                          setProof({
                            collection_name: "payment_proof",
                            url: uploaded.url,
                          });
                      } catch (_) {
                        setProof(null);
                      } finally {
                        setUploadingProof(false);
                      }
                    }}
                    isDisabled={uploadingProof}
                    classNames={{ input: "text-sm" }}
                  />
                  {uploadingProof && (
                    <div className="flex items-center gap-2 text-xs text-slate-500">
                      <Spinner size="sm" />
                      {t("uploading", {
                        defaultValue: "جاري رفع الإيصال...",
                      })}
                    </div>
                  )}
                  {!uploadingProof && !proof?.url && (
                    <p
                      className={`text-xs ${showValidation ? "text-red-600" : "text-amber-600"}`}
                    >
                      {t("proof_required", {
                        defaultValue: "رفع الإيصال مطلوب للتحويل البنكي",
                      })}
                    </p>
                  )}
                  {proof?.url && (
                    <button
                      type="button"
                      className="w-full flex flex-col items-center gap-2 rounded-xl border-2 border-dashed border-emerald-200 bg-emerald-50/50 p-4 hover:border-emerald-400 hover:bg-emerald-50 transition text-center"
                      onClick={() => setIsProofPreviewOpen(true)}
                    >
                      <Image
                        alt=""
                        src={proof.url}
                        width={160}
                        height={100}
                        className="rounded-lg object-contain max-h-28 bg-white border border-slate-100"
                      />
                      <span className="text-xs font-medium text-emerald-800">
                        {isRtl ? "معاينة الإيصال" : "Preview proof"}
                      </span>
                    </button>
                  )}
                </div>
              </section>
            )}
          </div>

          {/* أزرار الإجراءات — ثابتة أسفل الديالوغ */}
          <div className="shrink-0 flex flex-col-reverse sm:flex-row gap-3 p-4 pt-2 border-t border-slate-200 bg-slate-50/30 rounded-b-2xl">
            <Button
              variant="flat"
              className="flex-1 sm:flex-initial order-2 sm:order-1"
              onPress={() => {
                resetState();
                onOpenChange(false);
              }}
            >
              {t("cancel", { defaultValue: "إلغاء" })}
            </Button>
            <Button
              color="primary"
              isLoading={creating}
              isDisabled={!canSubmit}
              onPress={submitCreate}
              className="flex-1 sm:flex-initial order-1 sm:order-2 min-w-[140px]"
            >
              {t("confirm", { defaultValue: "تأكيد" })}
            </Button>
          </div>
        </>
      )}

      {isProofPreviewOpen && proof?.url && (
        <div
          className="fixed inset-0 z-60 flex items-center justify-center bg-black/70"
          onClick={() => setIsProofPreviewOpen(false)}
        >
          <div
            className="max-w-3xl w-[90vw] max-h-[90vh] bg-transparent flex flex-col items-end gap-3"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              type="button"
              className="px-3 py-1 rounded-full bg-white/90 text-xs font-semibold text-slate-700 shadow"
              onClick={() => setIsProofPreviewOpen(false)}
            >
              إغلاق
            </button>
            <Image
              alt="payment-proof-full"
              src={proof.url}
              width={1024}
              height={768}
              className="w-full h-full max-h-[80vh] object-contain rounded-2xl bg-slate-900/40"
            />
          </div>
        </div>
      )}

      {gatewayUrl && (
        <PaymentGatewayModal
          isOpen={showGatewayModal}
          onClose={() => {
            setShowGatewayModal(false);
            setGatewayUrl(null);
          }}
          gatewayUrl={gatewayUrl}
          isAr={lang === "ar"}
        />
      )}
    </div>
  </BaseModal>
  );
}
