Files
OnEverControl/frontend/src/components/modals/VehicleSearchModal.tsx
T

361 lines
14 KiB
TypeScript

// ==============================================================================
// 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<VehicleSearchModalProps> = ({
isOpen,
onClose,
onSelect,
esSalida = false,
initialSearch = '',
}) => {
const [query, setQuery] = useState<string>(initialSearch);
const [vehiculos, setVehiculos] = useState<VehicleSearchResult[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [selectedItem, setSelectedItem] = useState<VehicleSearchResult | null>(null);
const searchTimerRef = useRef<ReturnType<typeof setTimeout> | 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 (
<div
style={{
position: 'fixed',
inset: 0,
backgroundColor: 'rgba(0, 0, 0, 0.65)',
backdropFilter: 'blur(3px)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 1050,
padding: '1rem',
}}
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div
className="card"
style={{
width: '100%',
maxWidth: '880px',
maxHeight: '90vh',
display: 'flex',
flexDirection: 'column',
boxShadow: 'var(--shadow-xl)',
border: '1px solid var(--border-subtle)',
borderRadius: 'var(--radius-md)',
backgroundColor: 'var(--bg-surface)',
overflow: 'hidden',
animation: 'fadeIn 0.15s ease-out',
}}
>
{/* Header */}
<div
style={{
padding: '1rem 1.25rem',
borderBottom: '1px solid var(--border-subtle)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'var(--bg-app)',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
<span style={{ fontSize: '1.4rem' }}>🚗</span>
<div>
<h3 style={{ margin: 0, fontSize: '1.15rem', fontWeight: 700, color: 'var(--text-primary)' }}>
Búsqueda de Vehículos por Patente — {tituloModo}
</h3>
<p style={{ margin: 0, fontSize: '0.8rem', color: 'var(--text-secondary)' }}>
{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.'}
</p>
</div>
</div>
<button
type="button"
className="btn btn-secondary"
onClick={onClose}
style={{ minHeight: '36px', minWidth: '36px', padding: 0 }}
>
✕
</button>
</div>
{/* Input de Búsqueda */}
<div
style={{
padding: '0.85rem 1.25rem',
borderBottom: '1px solid var(--border-subtle)',
backgroundColor: 'var(--bg-surface)',
display: 'flex',
gap: '0.75rem',
alignItems: 'center',
}}
>
<div style={{ flex: 1, position: 'relative' }}>
<input
type="text"
className="input-field"
placeholder="🔍 Escriba parte de la patente, titular, modelo o DNI..."
value={query}
onChange={(e) => 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 && (
<button
type="button"
onClick={() => handleQueryChange('')}
style={{
position: 'absolute',
right: '0.75rem',
top: '50%',
transform: 'translateY(-50%)',
background: 'none',
border: 'none',
color: 'var(--text-muted)',
cursor: 'pointer',
fontSize: '1rem',
}}
>
✕
</button>
)}
</div>
<button
type="button"
className="btn btn-primary"
onClick={() => loadData(query)}
style={{ minHeight: '42px', padding: '0 1.25rem', fontWeight: 600 }}
>
Buscar
</button>
</div>
{/* Tabla */}
<div style={{ flex: 1, overflowY: 'auto', padding: '0.5rem 1.25rem' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '0.4rem 0' }}>
<span style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>
Coincidencias ({vehiculos.length}) {isLoading && '• Buscando...'}
</span>
<span style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>
Doble clic para cargar al formulario
</span>
</div>
<div
style={{
maxHeight: '400px',
overflowY: 'auto',
border: '1px solid var(--border-subtle)',
borderRadius: 'var(--radius-sm)',
backgroundColor: 'var(--bg-app)',
}}
>
{vehiculos.length === 0 && !isLoading ? (
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-secondary)', fontSize: '0.9rem' }}>
No se encontraron vehículos coincidentes con los filtros especificados.
</div>
) : (
<table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.85rem' }}>
<thead>
<tr style={{ backgroundColor: 'var(--bg-surface)', borderBottom: '1px solid var(--border-subtle)' }}>
<th style={{ padding: '0.55rem 0.75rem', width: '110px' }}>Patente</th>
<th style={{ padding: '0.55rem 0.75rem' }}>Marca / Modelo</th>
<th style={{ padding: '0.55rem 0.75rem' }}>Conductor / Titular</th>
<th style={{ padding: '0.55rem 0.75rem', width: '110px' }}>DNI</th>
{esSalida ? (
<>
<th style={{ padding: '0.55rem 0.75rem', width: '110px' }}>Lote</th>
<th style={{ padding: '0.55rem 0.75rem', width: '130px' }}>Ingreso</th>
</>
) : (
<th style={{ padding: '0.55rem 0.75rem', width: '130px' }}>Vigencia Seguro</th>
)}
</tr>
</thead>
<tbody>
{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 (
<tr
key={`${v.patente}-${v.ticket_id || idx}`}
onClick={() => 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',
}}
>
<td style={{ padding: '0.55rem 0.75rem' }}>
<span
style={{
display: 'inline-block',
padding: '0.2rem 0.5rem',
borderRadius: '4px',
backgroundColor: 'rgba(37, 99, 235, 0.15)',
color: 'var(--accent-primary)',
fontWeight: 800,
fontFamily: 'monospace',
fontSize: '0.95rem',
}}
>
{v.patente}
</span>
</td>
<td style={{ padding: '0.55rem 0.75rem', color: 'var(--text-primary)' }}>
{marcaModelo}
</td>
<td style={{ padding: '0.55rem 0.75rem', color: 'var(--text-primary)' }}>
{nombreCompleto}
</td>
<td style={{ padding: '0.55rem 0.75rem', color: 'var(--text-secondary)' }}>
{v.documento || '-'}
</td>
{esSalida ? (
<>
<td style={{ padding: '0.55rem 0.75rem' }}>
<span style={{ fontWeight: 600, color: 'var(--text-primary)' }}>
{v.lote ? `Lote ${v.lote}` : '-'}
</span>
</td>
<td style={{ padding: '0.55rem 0.75rem', fontSize: '0.78rem', color: 'var(--text-secondary)' }}>
{v.fecha_ingreso || '-'}
</td>
</>
) : (
<td style={{ padding: '0.55rem 0.75rem', fontSize: '0.8rem', color: 'var(--text-secondary)' }}>
{v.vigencia_seguro ? v.vigencia_seguro.slice(0, 10) : '-'}
</td>
)}
</tr>
);
})}
</tbody>
</table>
)}
</div>
</div>
{/* Footer */}
<div
style={{
padding: '1rem 1.25rem',
borderTop: '1px solid var(--border-subtle)',
backgroundColor: 'var(--bg-app)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
{selectedItem ? (
<span>
Seleccionado: <strong>{selectedItem.patente}</strong> ({selectedItem.marca} {selectedItem.modelo})
</span>
) : (
'Ningún vehículo seleccionado'
)}
</div>
<div style={{ display: 'flex', gap: '0.75rem' }}>
<button type="button" className="btn btn-secondary" onClick={onClose} style={{ minHeight: '44px', padding: '0 1.25rem' }}>
Cancelar
</button>
<button
type="button"
className="btn btn-primary"
disabled={!selectedItem}
onClick={() => handleConfirm()}
style={{ minHeight: '44px', padding: '0 1.5rem', fontWeight: 700 }}
>
✔ Seleccionar Patente
</button>
</div>
</div>
</div>
</div>
);
};