import { Autocomplete as MuiAutocomplete, TextField } from '@mui/material'
import _ from 'lodash'
import { useEffect, useMemo, useState } from 'react'

export default function AutocompleteSearch({
  name,
  value,
  onInputChange,
  onChange,
  label,
  options: _options,
  ...props
}) {
  const [options, setOptions] = useState([])

  const debouncedChangeHandler = useMemo(
    () =>
      _.debounce((e, newInput) => {
        onInputChange(newInput)
      }, 300),
    [],
  )

  useEffect(() => {
    if (!_options) return
    setOptions((prev) => [..._options])
  }, [_options])

  return (
    <MuiAutocomplete
      id="autocomplete-search"
      fullWidth
      getOptionLabel={(option) =>
        typeof option === 'string' ? option : option?.label
      }
      filterOptions={(x) => x}
      options={options || []}
      autoComplete
      includeInputInList
      filterSelectedOptions
      value={value}
      onChange={(event: any, newValue: any) => {
        if (!newValue) return
        // onInputChange(newValue)
        onChange(newValue)
      }}
      onInputChange={debouncedChangeHandler}
      renderInput={(params) => (
        <TextField {...params} label={label} fullWidth />
      )}
      renderOption={(props, option) => {
        return <li {...props}>{option?.label}</li>
      }}
      {...props}
    />
  )
}
