import * as React from 'react';
import { Input } from 'antd';
import { useDebounceFn } from 'ahooks';
import { useCallback, useState } from 'react';
import { InputProps } from 'antd/lib/input/Input';

export type ISearchBarProps = {
  placeholder?: string;
  allowClear?: boolean;
  fillOnSearch?: boolean;
  onSearch?: Function;
} & InputProps

export default ({
  placeholder = '请输入关键字',
  fillOnSearch = false,
  allowClear = true,
  onSearch = console.log,
  ...rest
}: ISearchBarProps) => {
  const [value, setValue] = useState('');
  const { run } = useDebounceFn(() => onSearch(value), { wait: 1000 });

  const onChange = useCallback((e: any) => {
    setValue(e.target.value);
    if (fillOnSearch) {
      run();
    }
  }, []);

  return (
    <Input.Search
      placeholder={placeholder}
      onChange={onChange}
      onSearch={() => onSearch(value)}
      allowClear={allowClear}
      {...rest}
    />
  );
};
