import { useEffect, useId, useMemo, useRef, useState } from "react"; import type { ChangeEvent, FormEvent, ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { AlertCircle, CheckCircle2, ExternalLink, Loader2, XCircle } from "lucide-react"; import { useQuoteIntlPayment, usePayIntlPayment, useCheckIntlPaymentCallback } from "../hooks/useVisaMasterPayments"; import type { PaymentCallbackResponse, PayResponse } from "../api/visaMasterPaymentsApi"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; // ─── Constants ──────────────────────────────────────────────────────────────── const MONTHS = [ { value: "01", label: "Ýanwar" }, { value: "02", label: "Fewral" }, { value: "03", label: "Mart" }, { value: "04", label: "Aprel" }, { value: "05", label: "Maý" }, { value: "06", label: "Iýun" }, { value: "07", label: "Iýul" }, { value: "08", label: "Awgust" }, { value: "09", label: "Sentýabr" }, { value: "10", label: "Oktýabr" }, { value: "11", label: "Noýabr" }, { value: "12", label: "Dekabr" }, ] as const; /** Digits with optional decimal part (max 2 digits). Accepts "." or ",". */ const AMOUNT_PATTERN = /^\d*([.,]\d{0,2})?$/; // ─── Helpers ────────────────────────────────────────────────────────────────── function currentMonthValue(): string { return String(new Date().getMonth() + 1).padStart(2, "0"); } function currentMonthLabel(monthValue: string, t: ReturnType["t"]): string { const month = MONTHS.find((m) => m.value === monthValue); return month ? t(`intlPayment.pay.months.${month.value}`, month.label) : monthValue; } /** Last day of the selected month in the current year, as YYYY-MM-DD */ function buildPaymentPeriod(monthValue: string): string { const year = new Date().getFullYear(); const month = parseInt(monthValue, 10); const lastDay = new Date(year, month, 0).getDate(); return `${year}-${monthValue}-${String(lastDay).padStart(2, "0")}`; } // Money math in minor units (tyn) to avoid floating point drift (0.1 + 0.2 problem) const toMinor = (value: number): number => Math.round(value * 100); const fromMinor = (minor: number): string => (minor / 100).toFixed(2); // ─── Layout helper ──────────────────────────────────────────────────────────── interface FieldRowProps { label: string; htmlFor: string; required?: boolean; children: ReactNode; } function FieldRow({ label, htmlFor, required, children }: FieldRowProps) { return (
{children}
); } // ─── Form (mounted only while the dialog is open → state resets automatically) ─ interface PayPayload { amountTmt: number; paymentPeriod: string; } interface PayFormProps { id: string; isPaying: boolean; onSubmit: (payload: PayPayload) => void; onCancel: () => void; } function PayForm({ id, isPaying, onSubmit, onCancel }: PayFormProps) { const { t } = useTranslation(); const uid = useId(); const monthId = `${uid}-month`; const amountId = `${uid}-amount`; const amountErrorId = `${uid}-amount-error`; const usdId = `${uid}-usd`; const totalId = `${uid}-total`; const [currentMonth] = useState(currentMonthValue); const [amountStr, setAmountStr] = useState(""); const { data: quote, isLoading: quoteLoading, isFetching: quoteFetching, isError: quoteError, refetch } = useQuoteIntlPayment(id); const amountTmt = Number(amountStr.replace(",", ".")) || 0; const { usdEquivalent, totalTmt } = useMemo(() => { if (!quote || amountTmt <= 0) return { usdEquivalent: "", totalTmt: "" }; // gbusFeeTmt/tvebFeeTmt are mutually exclusive on the backend (visa/master // orders set gbusFeeTmt, sber orders set tvebFeeTmt instead) - never both. const extraFeeTmt = quote.gbusFeeTmt ?? quote.tvebFeeTmt ?? 0; return { usdEquivalent: quote.exchangeRateUsd > 0 ? (amountTmt / quote.exchangeRateUsd).toFixed(2) : "", totalTmt: fromMinor(toMinor(amountTmt) + toMinor(quote.bankFeeTmt) + toMinor(extraFeeTmt)), }; }, [amountTmt, quote]); const amountError = quote && amountTmt > quote.maxAmountTmt ? t("intlPayment.pay.amountExceedsMax", "Möçber iň ýokary möçberden geçýär") : null; // Never allow paying without a fresh quote: the max-amount check depends on it. const canSubmit = !!quote && !quoteFetching && !isPaying && amountTmt > 0 && !amountError; function handleAmountChange(e: ChangeEvent) { const next = e.target.value; if (AMOUNT_PATTERN.test(next)) setAmountStr(next); } function handleSubmit(e: FormEvent) { e.preventDefault(); if (!canSubmit) return; onSubmit({ amountTmt, paymentPeriod: buildPaymentPeriod(currentMonth) }); } return (
{/* Quote info */} {quoteLoading ? (
{t("common.loading", "Ýüklenýär...")}
) : quoteError ? ( {t("intlPayment.pay.quoteError", "Kurs maglumatlary ýüklenmedi")} ) : quote ? (
1 USD
{quote.exchangeRateUsd} TMT
{t("intlPayment.pay.bankFee", "BANKYŇ TUTUMY")}
{quote.bankFeeTmt} TMT
{quote.gbusFeeTmt != null && (
{t("intlPayment.pay.gbusFee", "GBÜS TUTUMY")}
{quote.gbusFeeTmt} TMT
)} {quote.tvebFeeTmt != null && (
{t("intlPayment.pay.tvebFee", "TVEB TUTUMY")}
{quote.tvebFeeTmt} TMT
)}
) : null} {/* Töleg aý */} {/* Töleg möçberi */} {amountError ? ( ) : ( quote && (

{t("intlPayment.pay.maxAmount", "Iň ýokary möçberi")}: {quote.maxAmountTmt} TMT

) )}
{/* USD ekwalendi */} {/* Jemi */}
); } // ─── Dialog ─────────────────────────────────────────────────────────────────── interface PayDialogProps { id: string; open: boolean; onOpenChange: (open: boolean) => void; } export function PayDialog({ id, open, onOpenChange }: PayDialogProps) { const { t } = useTranslation(); const { mutate: pay, isPending: isPaying } = usePayIntlPayment(); const { mutate: checkCallback, isPending: isChecking } = useCheckIntlPaymentCallback(); const [paymentInit, setPaymentInit] = useState(null); const [paymentResult, setPaymentResult] = useState(null); // Tracks the open bank-page popup so it can be polled for navigation back // to successUrl (GBÜS's callback) - see watchBankPage. const popupRef = useRef(null); const pollRef = useRef | null>(null); // The parent passes id="" as soon as it closes the dialog. Keep the last real id // so the content doesn't flicker (quote disappears) during the close animation. const [stableId, setStableId] = useState(id); function stopWatchingBankPage() { if (pollRef.current != null) { clearInterval(pollRef.current); pollRef.current = null; } popupRef.current = null; } // Once GBÜS returns to its backend callback URL, send the popup to our // callback page. That page requests the final payment state and informs the user. function watchBankPage(popup: Window, successUrl: string, paymentId: number) { stopWatchingBankPage(); popupRef.current = popup; pollRef.current = setInterval(() => { const win = popupRef.current; if (!win || win.closed) { stopWatchingBankPage(); return; } let href: string; try { href = win.location.href; } catch { return; } if (href.startsWith(successUrl)) { stopWatchingBankPage(); win.location.replace( new URL(`visa-master/payment-callback?paymentId=${paymentId}`, `${window.location.origin}${import.meta.env.BASE_URL}`).href, ); } }, 1500); } // Stop polling on unmount so a closed dialog never keeps a timer alive. useEffect(() => stopWatchingBankPage, []); useEffect(() => { if (!id || id === stableId) return; setStableId(id); setPaymentInit(null); setPaymentResult(null); stopWatchingBankPage(); }, [id, stableId]); // Block every close path (ESC, overlay click, X button) while the payment request is in flight. function handleOpenChange(next: boolean) { if (isPaying || isChecking) return; if (!next) { setPaymentInit(null); setPaymentResult(null); stopWatchingBankPage(); } onOpenChange(next); } function handleSubmit(payload: PayPayload) { // Reserving the window while this click is still a user gesture prevents // browsers from blocking the bank popup after the async status check. const bankPopup = window.open("", "_blank"); if (bankPopup) { try { bankPopup.opener = null; } catch { // Some browsers disallow this; navigation can still continue. } } pay( { id: stableId, payload }, { onSuccess: (data) => { setPaymentInit(data); setPaymentResult(null); const paymentId = data.paymentId; if (!paymentId) { bankPopup?.close(); return; } checkCallback(paymentId, { onSuccess: (result) => { setPaymentResult(result); if (result.paid || !data.formUrl) { bankPopup?.close(); return; } if (!bankPopup) { window.location.href = data.formUrl; return; } bankPopup.location.href = data.formUrl; if (data.successUrl) watchBankPage(bankPopup, data.successUrl, paymentId); }, onError: () => bankPopup?.close(), }); }, onError: () => bankPopup?.close(), }, ); } return ( {t("intlPayment.pay.title", "Töleg")} {paymentInit ? t("intlPayment.pay.statusInstruction", "Bank sahypasynda tölegi tamamlandan soň netijäni barlaň.") : t("intlPayment.pay.instruction", 'Ýerine ýetirmek üçin "dowam et" düwmä basyň.')} {paymentInit ? (
{isChecking ? : } {isChecking ? t("intlPayment.pay.checkingStatus", "Töleg ýagdaýy barlanýar...") : paymentResult?.paid ? t("intlPayment.paySuccess", "Töleg üstünlikli amala aşyryldy") : t("intlPayment.pay.bankPageOpened", "Bankyň töleg sahypasy açyldy.")} {paymentResult ? ( {paymentResult.paid ? : } {paymentResult.data} ) : null}
) : ( handleOpenChange(false)} /> )}
); }