import { Search } from '@mui/icons-material'
import { InputAdornment } from '@mui/material'
import _ from 'lodash'
import { ReactNode, useMemo, useState } from 'react'
import { TextField } from '../Input'
import { ITextFieldProps } from '../Input/TextField'

interface SearchBarProps {
  onSearch: (v: string) => void
  label?: ReactNode
  placeholder?: string
  value?: string
  textFieldProps?: ITextFieldProps
}

export default function SearchBar({
  onSearch,
  label,
  placeholder = 'Search',
  value,
  ...restProps
}: SearchBarProps) {
  const [, setSearch] = useState(value || '')

  const debouncedChangeHandler = useMemo(
    () =>
      _.debounce((e) => {
        setSearch(e.target.value)
        onSearch(e.target.value)
      }, 300),
    [],
  )

  return (
    <TextField
      label={label}
      placeholder={placeholder}
      onChange={debouncedChangeHandler}
      defaultValue={value || ''}
      InputProps={{
        endAdornment: (
          <InputAdornment position="end">
            <Search />
          </InputAdornment>
        ),
      }}
      {...restProps.textFieldProps}
    />
  )
}
