import { useState, useRef } from "react"; import InputAdornment from "@mui/material/InputAdornment"; import IconButton from "@mui/material/IconButton"; import Tooltip from "@mui/material/Tooltip"; import Menu from "@mui/material/Menu"; import MenuItem from "@mui/material/MenuItem"; import Typography from "@mui/material/Typography"; import Box from "@mui/material/Box"; import CircularProgress from "@mui/material/CircularProgress"; import { jsonQuery } from "../lib/apiAdapter"; import { useAlert } from "../context/AlertContext"; /** Normalized company record returned by the /api/admin/ares proxy. */ export interface AresCompany { ico: string; dic: string | null; name: string; street: string; city: string; postal_code: string; country: string; } interface AresAdornmentProps { /** "ico" looks the query up directly; "name" searches and offers a picker. */ mode: "ico" | "name"; /** Current value of the host field (IČO or name fragment). */ query: string; /** Called with the chosen company — the modal prefills its form from it. */ onFill: (company: AresCompany) => void; } /** * "ARES" end-adornment button for the Název/IČO fields of the customer and * supplier modals. IČO mode fetches the subject directly; name mode searches * ARES and shows a result picker (filling straight away on a single hit). * Pass via the TextField's `InputProps.endAdornment`. */ export default function AresAdornment({ mode, query, onFill, }: AresAdornmentProps) { const alert = useAlert(); const [loading, setLoading] = useState(false); const [results, setResults] = useState([]); const [menuOpen, setMenuOpen] = useState(false); const anchorRef = useRef(null); const trimmed = query.trim(); const enabled = mode === "ico" ? /^\d{8}$/.test(trimmed.replace(/\s+/g, "")) : trimmed.length >= 2; const tooltip = mode === "ico" ? enabled ? "Načíst údaje z ARES podle IČO" : "Vyplňte 8místné IČO" : enabled ? "Vyhledat firmu v ARES podle názvu" : "Vyplňte alespoň 2 znaky názvu"; const lookup = async () => { if (!enabled || loading) return; setLoading(true); try { if (mode === "ico") { const company = await jsonQuery( `/api/admin/ares/ico/${encodeURIComponent(trimmed.replace(/\s+/g, ""))}`, ); onFill(company); } else { const found = await jsonQuery( `/api/admin/ares/search?q=${encodeURIComponent(trimmed)}`, ); if (found.length === 0) { alert.error("Žádná firma tohoto názvu nebyla v ARES nalezena"); } else if (found.length === 1) { onFill(found[0]); } else { setResults(found); setMenuOpen(true); } } } catch (e) { alert.error( e instanceof Error ? e.message : "Registr ARES je nedostupný", ); } finally { setLoading(false); } }; return ( {loading ? ( ) : ( ARES )} setMenuOpen(false)} > {results.map((c) => ( { setMenuOpen(false); onFill(c); }} > {c.name} IČO {c.ico} {c.city ? ` · ${c.city}` : ""} ))} ); }