import React, { Component } from 'react';
import styles from './style.css';
import SelectIcon from './images/more_item_btn@2x.png';

class Select extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showOptions: false,
    };
  }

  componentWillMount() {
    console.log(this.props.children);
    if (this.props.children.length) {
      this.props.onChange([this.props.children[0].props.value]);
    }
  }

  toggleOptions = () => {
    console.log('in click');
    this.setState(({ showOptions }) => ({
      showOptions: !showOptions,
    }));
  };
  selectHandle = (e, val) => {
    e.preventDefault();
    e.stopPropagation();
    console.log(val);
    // this.setState({
    //   showOptions: false,
    // });
    const { value } = this.props;
    if (value.indexOf(val) !== -1) {
      this.props.onChange(value.filter(i => i !== val));
    } else {
      this.props.onChange([...value, val]);
    }
  };
  render() {
    const { showOptions } = this.state;
    const { value } = this.props;
    return (
      <div className={styles.selectWrap} onClick={this.toggleOptions}>
        <div className={styles.selectValue}>
          <div className={styles.selectValueOption}>{value.join(',')}</div>
          {showOptions && (
            <div className={styles.selectOptionsBox}>
              {this.props.children.map(
                (i, idx) =>
                  value.indexOf(i.props.value) !== -1 ? (
                    <div
                      className={styles.selectOptionChecked}
                      key={idx}
                      onClick={e => this.selectHandle(e, i.props.value)}
                    >
                      {i}
                      <div className={styles.selected}>
                        <div className={styles.selectedInner} />
                      </div>
                    </div>
                  ) : (
                    <div
                      className={styles.selectOption}
                      key={idx}
                      onClick={e => this.selectHandle(e, i.props.value)}
                    >
                      {i}
                    </div>
                  )
              )}
            </div>
          )}
        </div>

        <div className={styles.selectIcon}>
          <img src={SelectIcon} alt="" />
        </div>
      </div>
    );
  }
}

export default Select;
