import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input } from 'patd';
import styles from './InputMenu.scss';

export default class InputMenu extends Component {
  static defaultProps = {
    datas: [],
    value: '',
    width: 200,
    onChange: () => { },
  }
  static propTypes = {
    datas: PropTypes.array.isRequired,
    onChange: PropTypes.func
  }
  state = {
    show: false,
  }

  setValue = (value) => {
    this.props.onChange(value);
  }

  blur = () => {
    setTimeout(() => {
      this.setState({ show: false });
    }, 100);
  }

  changeMenu = (value, item) => {
    this.props.onChange(value, item);
    this.setState({
      show: false,
    });
  }

  render() {
    const {
      datas, width, InputMenuStyle, value, ...others
    } = this.props;
    const { show } = this.state;
    return (
      <div className={styles['paui-inputmenu']}>
        <Input
          {...others}
          width={width}
          autoComplete="off"
          value={value}
          name="input"
          onFocus={() => this.setState({ show: true })}
          onBlur={this.blur}
          style={InputMenuStyle}
          onChange={e => this.setValue(e.target.value)}
        />
        {show && <ul className={styles['paui-menu']} style={{ width }}>
          {datas.map(item => (
            <li
              className={styles['paui-menu-item']}
              key={item.id}
              onClick={() => this.changeMenu(item.text, item)}
            >
              {item.text}
            </li>
          ))
          }
        </ul>}
      </div>
    );
  }
}
