"use client"; import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from "react"; import { Pencil } from "lucide-react"; import type { SortingState } from "@tanstack/react-table"; import { Button } from "@/app/components/ui/button"; import { SortableHead, sortRows } from "@/app/components/ui/sortable-head"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/app/components/ui/select"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from "@/app/components/ui/dialog"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/app/components/ui/table"; import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states"; import { createBank, listBankCountries, listBanks, updateBank, type BankRowPayload, } from "@/app/lib/services/adminBank"; import type { BankCountry, BankRow } from "@/app/lib/types"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { Translate } from "@/app/lib/i18n/t"; // Bank tab of the /reference page (add-admin-bank-reference, spec "admin-portal-reference-ui"). // Banks are listed per active country; code is unique within a country and, like the other // reference tables, immutable after create. Country is fixed per bank, so the dialog shows it // read-only. The page's "Add row" button drives `adding`; the panel owns the dialog. type OptionalField = "swiftCode" | "bnmCode" | "bankid" | "branchCode" | "messageTag"; const OPTIONAL_FIELDS: { field: OptionalField; label: string; maxLength: number }[] = [ { field: "swiftCode", label: "RfrSwiftCode", maxLength: 255 }, { field: "bnmCode", label: "RfrBnmCode", maxLength: 200 }, { field: "bankid", label: "RfrBankId", maxLength: 255 }, { field: "branchCode", label: "RfrBranchCode", maxLength: 20 }, { field: "messageTag", label: "RfrMessageTag", maxLength: 255 }, ]; const COLUMNS: { field: keyof BankRow; label: string }[] = [ { field: "code", label: "Code" }, { field: "name", label: "CatName" }, { field: "swiftCode", label: "RfrSwift" }, { field: "bnmCode", label: "RfrBnmCode" }, { field: "bankid", label: "RfrBankId" }, { field: "branchCode", label: "RfrBranchCode" }, { field: "messageTag", label: "RfrMessageTag" }, ]; function messageOf(err: unknown, fallback: string): string { return err instanceof Error ? err.message : fallback; } function BankFormDialog({ country, bank, onClose, onSaved, t, }: { country: BankCountry; bank: BankRow | null; onClose: () => void; onSaved: () => void; t: Translate; }) { const isEdit = bank != null; const codeRef = useRef(null); const nameRef = useRef(null); const [values, setValues] = useState>(() => { const initial: Record = { code: bank?.code ?? "", name: bank?.name ?? "" }; for (const { field } of OPTIONAL_FIELDS) initial[field] = bank?.[field] ?? ""; return initial; }); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); function setField(field: string, value: string) { setValues((prev) => ({ ...prev, [field]: value })); } async function handleSubmit(event: FormEvent) { event.preventDefault(); const code = values.code.trim(); const name = values.name.trim(); if (!code || !name) { setError("RfrBankCodeNameRequired"); return; } // Every optional field is sent, "" included, so clearing a field on edit really clears it. const payload: BankRowPayload = { code, name, countryCode: country.code }; for (const { field } of OPTIONAL_FIELDS) payload[field] = values[field].trim(); setSaving(true); setError(null); try { if (isEdit && bank.id != null) { await updateBank(bank.id, payload); } else { await createBank(payload); } onSaved(); onClose(); } catch (err) { // A duplicate-code 409 / validation 422 is reported inline; the dialog stays open. setError(messageOf(err, "RfrBankSaveFailed")); } finally { setSaving(false); } } return ( !open && onClose()}> { event.preventDefault(); // Radix's default auto-focus lands on the first focusable field, which is the // read-only Country input (Code too, on edit) — focus the first EDITABLE field instead. (isEdit ? nameRef : codeRef).current?.focus(); }} > {t(isEdit ? "RfrBankEditTitle" : "RfrBankAddTitle", isEdit ? { code: bank.code } : { country: country.name })} {error && }
setField("code", e.target.value)} className={isEdit ? "opacity-70" : undefined} /> {isEdit && (

{t("RfrBankCodeImmutableNote")}

)}
setField("name", e.target.value)} />
{OPTIONAL_FIELDS.map(({ field, label, maxLength }) => (
setField(field, e.target.value)} />
))}
); } export function BankPanel({ adding, onAddingChange, }: { adding: boolean; onAddingChange: (open: boolean) => void; }) { const t = useT(); const [countries, setCountries] = useState(null); const [countryCode, setCountryCode] = useState(""); const [rows, setRows] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [reloadKey, setReloadKey] = useState(0); const [query, setQuery] = useState(""); const [editing, setEditing] = useState(null); const [sorting, setSorting] = useState([]); const refetch = useCallback(() => setReloadKey((k) => k + 1), []); const country = countries?.find((c) => c.code === countryCode) ?? null; // Add was requested (countries still loading, load failed, or none active) before a country was // ready: treat the click as a no-op instead of leaving it pending for a delayed pop-up once a // country becomes available. useEffect(() => { if (adding && !country) onAddingChange(false); }, [adding, country, onAddingChange]); // Countries load once; a retry after a failed load re-runs this (countries stays null). useEffect(() => { if (countries) return; let cancelled = false; // eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the fetch below; the fetch itself is the actual synchronization. setLoading(true); setError(null); listBankCountries() .then((list) => { if (cancelled) return; setCountries(list); if (list.length > 0) setCountryCode(list[0].code); else setLoading(false); }) .catch((err: unknown) => { if (cancelled) return; setError(messageOf(err, "RfrBankLoadCountriesFailed")); setLoading(false); }); return () => { cancelled = true; }; }, [countries, reloadKey]); useEffect(() => { if (!countryCode) return; let cancelled = false; // eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the fetch below; the fetch itself is the actual synchronization. setLoading(true); setError(null); listBanks(countryCode) .then((result) => { if (!cancelled) setRows(result); }) .catch((err: unknown) => { if (!cancelled) setError(messageOf(err, "RfrBankLoadFailed")); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [countryCode, reloadKey]); const filtered = useMemo(() => { const q = query.trim().toLowerCase(); const matched = q ? rows.filter((r) => r.code.toLowerCase().includes(q) || r.name.toLowerCase().includes(q)) : rows; const getters = Object.fromEntries(COLUMNS.map((c) => [c.field, (r: BankRow) => r[c.field]])); return sortRows(matched, sorting, getters); }, [rows, query, sorting]); const total = rows.length; const shown = filtered.length; const countLabel = query.trim() ? t("RfrBankCountFiltered", { shown, total }) : t(total === 1 ? "RfrBankCountOne" : "RfrBankCountMany", { count: total }); function closeDialog() { setEditing(null); onAddingChange(false); } if (countries && countries.length === 0) { return ( ); } return ( <>
setQuery(e.target.value)} />

{loading || error ? "" : countLabel}

{error && } {/* Gated on !loading && !error so a failed or in-flight fetch never shows another country's rows under this country's filter. */} {loading ? ( ) : error ? null : rows.length === 0 ? ( ) : filtered.length === 0 ? ( ) : (
{COLUMNS.map((col) => ( ))} {t("CatActions")} {filtered.map((row) => ( {COLUMNS.map((col) => ( {row[col.field] || "—"} ))}
))}
)} {country && (adding || editing) && ( )} ); }