import React from "react" import { CircularProgress } from "@mui/material" import { AutocompleteField, AutocompleteText } from "./style" import { DataOption } from "../data-table" export interface AutocompleteProps { style?: React.CSSProperties, className?: string, disabled?: boolean, multiple?: boolean, limitTags?: number, label?: string, value: DataOption | DataOption[], options: (inputText: string) => Promise onChange: (value: DataOption | DataOption[] | null) => void, } export const Autocomplete: React.FC = ({ style, className, disabled, multiple, limitTags, label, value, options, onChange }) => { const [loading, setLoading] = React.useState(false); const [optionItems, setOptionItems] = React.useState(); const [timer, setTimer] = React.useState(); React.useEffect(() => { if (!!options && !optionItems) { setOptionItems([]); handleLoad( value ? Array.isArray(value) ? value.length > 0 && value[0].label ? value[0].label : '' : value.label ? value.label : '' : '' ); } }, [options, optionItems, setOptionItems]) const handleLoad = (inputText: string) => { setLoading(true); options(inputText) .then(result => { if (!!result) { setOptionItems(result) } }) .finally(() => { setLoading(false); }) } const getValue = () => { return value ? value : null; } const handleChange = (event: any, value: any) => { onChange(value) } const handleInputChange = (event: any) => { if (timer) { clearTimeout(timer); } setTimer( setTimeout(() => { handleLoad(event.target.value) }, 500) ) } return ( option.label} getOptionDisabled={(option: any) => !!option.disabled} isOptionEqualToValue={(option: any, value: any) => (option.key && option.value[option.key] === value.value[option.key]) || (option.label === value.label)} value={getValue()} onChange={handleChange} renderInput={(params: any) => { const endAdornment = params.InputProps.endAdornment as any; return ( {loading ? : null} {endAdornment} ), }} label={label} onChange={handleInputChange} /> ) }} /> ) }