import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useDebounceFn } from 'ahooks';
import { Input } from 'antd';
import Icon from '@/tenants-ui/Icon';
import cx from 'classnames';
import styles from './index.less';

export default ({ placeholder, onSearch, onCancel }) => {
  const ref = useRef();
  const [focus, setFocus] = useState(false);
  const [searchValue, setSearchValue] = useState('');

  const { run } = useDebounceFn(
    (val) => {
      onSearch(val);
    },
    {
      wait: 500,
    },
  );

  const handleClose = useCallback((e) => {
    if (e.keyCode === 27) {
      setFocus(false);
      setSearchValue('');
      onCancel();
      ref.current.blur();
    }
  }, []);

  useEffect(() => {
    document.addEventListener('keyup', handleClose);
    return () => {
      document.removeEventListener('keyup', handleClose);
    };
  }, []);

  return (
    <div
      className={cx(styles.searchInput, {
        [styles.focus]: focus,
      })}
    >
      <Icon type="search" style={{ color: '#C4C4C4' }} />
      <div className={styles.input}>
        <Input
          style={{ width: '100%' }}
          ref={ref}
          size="large"
          bordered={false}
          onFocus={() => setFocus(true)}
          onBlur={() => {
            if (!searchValue) {
              setFocus(false);
            }
          }}
          value={searchValue}
          placeholder={placeholder}
          onChange={(e) => {
            const val = e.target.value;
            setSearchValue(val);
            //run(val);
            onSearch(val);
          }}
        />
      </div>
      <div className={styles.cancel} onClick={() => handleClose({ keyCode: 27 })}>
        <Icon type="backward" />
        取消搜索
      </div>
    </div>
  );
};
