import React, { useRef } from 'react';

import {
  AutoComplete,
  Input,
} from 'antd';
import classNames from 'classnames';
import PropType from 'prop-types';
import useMergeValue from 'use-merge-value';

import { SearchOutlined } from '@ant-design/icons';

import styles from './index.less';

const HeaderSearch = props => {
  const {
    className,
    defaultValue,
    onVisibleChange,
    placeholder,
    open,
    defaultOpen,
    ...restProps
  } = props;

  const inputRef = useRef(null);

  const [value, setValue] = useMergeValue(defaultValue, {
    value: props.value,
    onChange: props.onChange,
  });

  const [searchMode, setSearchMode] = useMergeValue(defaultOpen || true, {
    value: props.open,
    onChange: onVisibleChange,
  });

  const inputClass = classNames(styles.input, styles.search, {
    // [styles.show]: searchMode,
  });

  return (
    <div
      className={classNames(className, styles.headerSearch)}
      onClick={() => {
        // setSearchMode(true);
        if (searchMode && inputRef.current) {
          inputRef.current.focus();
        }
      }}
      onTransitionEnd={({ propertyName }) => {
        if (propertyName === 'width' && !searchMode) {
          if (onVisibleChange) {
            onVisibleChange(searchMode);
          }
        }
      }}
    >
      <AutoComplete
        key="AutoComplete"
        // className={inputClass}
        value={value}
        style={{
          height: 28,
          marginTop: -6,
        }}
        options={restProps.options}
        onChange={setValue}
        onSelect={restProps.onSelect}
      >
        <Input
          ref={inputRef}
          defaultValue={defaultValue}
          aria-label={placeholder}
          placeholder={placeholder}
          className={inputClass}
          allowClear={true}
          onKeyDown={e => {
            if (e.key === 'Enter') {
              if (restProps.onSearch) {
                restProps.onSearch(value);
              }
            }
          }}
          onBlur={() => {
            setSearchMode(false);
          }}
          prefix={<SearchOutlined className="site-form-item-icon" />}
        />
      </AutoComplete>
    </div>
  );
};

HeaderSearch.propTypes = {
  onSearch: PropType.func,
  onChange: PropType.func,
  onSelect: PropType.func,
  onVisibleChange: PropType.func,
  className: PropType.string,
  placeholder: PropType.string,
  options: PropType.array,
  defaultOpen: PropType.bool,
  open: PropType.bool,
  defaultValue: PropType.string,
  value: PropType.string,
};
export default HeaderSearch;
