import React, { useState, useEffect, useRef } from 'react'; import { Search, ChevronDown, Check } from 'lucide-react'; const AutocompleteInput = ({ label, value, onChange, options = [], onSelect, placeholder = "Pesquisar...", displayKey = "label", // key to show in list valueKey = "value", // key to use for value searchKeys = [], // keys to search in. if empty, searches displayKey className = "", disabled = false, required = false }) => { const [isOpen, setIsOpen] = useState(false); const [searchTerm, setSearchTerm] = useState(value || ''); const wrapperRef = useRef(null); useEffect(() => { setSearchTerm(value || ''); }, [value]); useEffect(() => { const handleClickOutside = (event) => { if (wrapperRef.current && !wrapperRef.current.contains(event.target)) { setIsOpen(false); } }; document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); const filteredOptions = options.filter(option => { if (!searchTerm) return true; const term = searchTerm.toLowerCase(); // If searchKeys provided, search in those if (searchKeys.length > 0) { return searchKeys.some(key => { const val = option[key]; return val && String(val).toLowerCase().includes(term); }); } // Otherwise search in displayKey or direct string const label = typeof option === 'object' ? option[displayKey] : option; return String(label).toLowerCase().includes(term); }); const handleSelect = (option) => { const displayVal = typeof option === 'object' ? option[displayKey] : option; const actualVal = typeof option === 'object' ? (option[valueKey] || option[displayKey]) : option; setSearchTerm(displayVal); onChange(displayVal); // Update the input value if (onSelect) onSelect(option); // Trigger specific selection logic setIsOpen(false); }; return (
{label && ( )}
{ setSearchTerm(e.target.value); onChange(e.target.value); setIsOpen(true); }} onFocus={() => setIsOpen(true)} disabled={disabled} /> {isOpen && filteredOptions.length > 0 && (
    {filteredOptions.map((option, index) => { const display = typeof option === 'object' ? option[displayKey] : option; const isSelected = display === value; return (
  • handleSelect(option)} > {display} {isSelected && }
  • ); })}
)} {isOpen && filteredOptions.length === 0 && searchTerm && (
Sem resultados
)}
); }; export default AutocompleteInput;