// ============================================================================== // Modal de Búsqueda Predictiva de Vehículos por Patente // Paridad 1:1 con DialogoBuscarPatente (pct_dialogs.py - OneverAccess / OemspotPySYS) // ============================================================================== import React, { useState, useEffect, useRef, useCallback } from 'react'; import { VehicleSearchResult } from '../../types'; import { accessApi } from '../../api/accessApi'; interface VehicleSearchModalProps { isOpen: boolean; onClose: () => void; onSelect: (vehiculo: VehicleSearchResult) => void; esSalida?: boolean; initialSearch?: string; } export const VehicleSearchModal: React.FC = ({ isOpen, onClose, onSelect, esSalida = false, initialSearch = '', }) => { const [query, setQuery] = useState(initialSearch); const [vehiculos, setVehiculos] = useState([]); const [isLoading, setIsLoading] = useState(false); const [selectedItem, setSelectedItem] = useState(null); const searchTimerRef = useRef | null>(null); const loadData = useCallback(async (searchTerm: string) => { setIsLoading(true); try { const data = await accessApi.searchVehicles(searchTerm, esSalida, 50); setVehiculos(data); if (data.length > 0) { setSelectedItem((prev) => (prev ? (data.find((v) => v.patente === prev.patente) || data[0]) : data[0])); } else { setSelectedItem(null); } } catch (e) { console.error('Error al buscar vehículos:', e); setVehiculos([]); setSelectedItem(null); } finally { setIsLoading(false); } }, [esSalida]); useEffect(() => { if (isOpen) { const initUpper = (initialSearch || '').toUpperCase().trim(); setQuery(initUpper); loadData(initUpper); } else { setQuery(''); setSelectedItem(null); } }, [isOpen, initialSearch, loadData]); const handleQueryChange = (text: string) => { const upper = text.toUpperCase(); setQuery(upper); if (searchTimerRef.current) { clearTimeout(searchTimerRef.current); } searchTimerRef.current = setTimeout(() => { loadData(upper); }, 250); }; const handleConfirm = (item?: VehicleSearchResult | null) => { const target = item || selectedItem; if (!target) return; onSelect(target); onClose(); }; if (!isOpen) return null; const tituloModo = esSalida ? 'Salida (Vehículos en Predio)' : 'Entrada (Padrón de Vehículos)'; return (
{ if (e.target === e.currentTarget) onClose(); }} >
{/* Header */}
🚗

Búsqueda de Vehículos por Patente — {tituloModo}

{esSalida ? 'Filtre por patente, conductor o lote para seleccionar vehículos con ticket activo.' : 'Filtre en el padrón de automotores registrados con datos de pólizas y titulares.'}

{/* Input de Búsqueda */}
handleQueryChange(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') loadData(query); }} autoFocus style={{ paddingRight: query ? '2.5rem' : '1rem', minHeight: '42px', textTransform: 'uppercase', fontWeight: 600, letterSpacing: '1px', }} /> {query && ( )}
{/* Tabla */}
Coincidencias ({vehiculos.length}) {isLoading && '• Buscando...'} Doble clic para cargar al formulario
{vehiculos.length === 0 && !isLoading ? (
No se encontraron vehículos coincidentes con los filtros especificados.
) : ( {esSalida ? ( <> ) : ( )} {vehiculos.map((v, idx) => { const isSel = selectedItem?.patente === v.patente; const nombreCompleto = `${v.apellido} ${v.nombre}`.trim() || '-'; const marcaModelo = `${v.marca} ${v.modelo}`.trim() || '-'; return ( setSelectedItem(v)} onDoubleClick={() => handleConfirm(v)} style={{ cursor: 'pointer', backgroundColor: isSel ? 'rgba(37, 99, 235, 0.18)' : 'transparent', borderBottom: '1px solid var(--border-subtle)', fontWeight: isSel ? 700 : 400, borderLeft: isSel ? '4px solid var(--accent-primary)' : '4px solid transparent', transition: 'background 0.1s ease', }} > {esSalida ? ( <> ) : ( )} ); })}
Patente Marca / Modelo Conductor / Titular DNILote IngresoVigencia Seguro
{v.patente} {marcaModelo} {nombreCompleto} {v.documento || '-'} {v.lote ? `Lote ${v.lote}` : '-'} {v.fecha_ingreso || '-'} {v.vigencia_seguro ? v.vigencia_seguro.slice(0, 10) : '-'}
)}
{/* Footer */}
{selectedItem ? ( Seleccionado: {selectedItem.patente} ({selectedItem.marca} {selectedItem.modelo}) ) : ( 'Ningún vehículo seleccionado' )}
); };