import _ from "lodash";
import React, { Component } from "react";
import { ListItem, Menu } from "..";

class DropdownSelector extends Component {
  constructor(props) {
    super(props);

    this.state = {
      choice: props.choice,
      text: props.text
    };

    this.noteListSelection = this.noteListSelection.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.choice !== nextProps.choice) {
      this.setState({ choice: nextProps.choice });
    }
  }

  noteListSelection(id) {
    this.setState(
      {
        choice: id
      },
      () => this.props.onChange(this.state.choice)
    );
  }

  render() {
    const text = this.state.choice
      ? _.filter(this.props.items, i => i.id === this.state.choice)
      : [{ name: this.props.text }];

    return (
      <Menu
        label={text.length ? text[0].name : this.props.text}
        style={{ width: "100%" }}
      >
        <div style={{ height: 200, overflowY: "scroll" }}>
          {this.props.items.map(itm => (
            <ListItem
              key={itm.id}
              onClick={() => this.noteListSelection(itm.id)}
            >
              {this.props.showId ? `(${itm.id}) ` : null}
              {itm.name}
            </ListItem>
          ))}
        </div>
      </Menu>
    );
  }
}

DropdownSelector.defaultProps = {
  items: [],
  choice: false,
  showId: false,
  text: "Choose an item...",
  onChange: () => false
};

export default DropdownSelector;
