import React, { Component } from "react";
import { ListItem, Menu } from "../index";
import style from "./style";

/**
 * The SelectField component is used to replace the <select> menu.
 * @param {object} props The props
 * @returns {function} The component
 */
class SelectField extends Component {
  constructor(props) {
    super(props);

    this.state = {
      id: false,
      text: props.children || props.label
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(id) {
    const { menuItems, onChange } = this.props;
    const item = menuItems.filter(itm => itm.id === id)[0];
    this.setState({
      id: item.id,
      text: item.name
    });

    onChange(id);
  }

  render() {
    const { menuItems } = this.props;
    const { text } = this.state;

    return (
      <div
        role="group"
        {...this.props}
        style={{ ...style.selectField, ...this.props.style, cursor: "pointer" }}
      >
        <Menu
          label={this.props.label || text}
          style={{ width: "100%", display: "inline-block" }}
        >
          {menuItems
            ? menuItems.map(itm => (
                <ListItem
                  key={itm.id}
                  onClick={() => this.handleChange(itm.id)}
                >
                  {itm.name}
                </ListItem>
              ))
            : null}
        </Menu>
      </div>
    );
  }
}

SelectField.defaultProps = {
  onChange: () => false,
  menuItems: [{ id: false, text: "" }]
};

export default SelectField;
