import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import sortBy from 'lodash/sortBy';
import Admin from './../admin'
import { fetchEntities } from '../actions/index'

interface ModalSelectProps {
  fetchEntities: any;
  fetchOptions: string;
  header: string;
  options: any[];
  pages: any[];
  property: string;
  func: any;
}

interface ModalSelectState {
  fetching: boolean;
  options: any[];
  searchText: string;
}

class ModalSelect extends React.Component<ModalSelectProps, ModalSelectState> {

  constructor(props) {
    super(props);
    this.state = {
      fetching: !!this.props.fetchOptions,
      options: this.props.options || [],
      searchText: ""
    };
  }

  componentDidMount() {
    if (this.props.fetchOptions) {
      this.props.fetchEntities(this.props.fetchOptions).then(() => {
        this.setState({
          fetching: false,
          options: this.props[this.props.fetchOptions]
        });
      });
    }
  }

  render() {
    return(
      <div className="modal-select">
        { Admin.renderSpinner(this.state.fetching) }
        { Admin.renderGrayedOut(this.state.fetching) }
        { this.renderHeader() }
        <input className="search-box" onChange={ Admin.changeSearchText.bind(this) } value={ this.state.searchText } />
        <ul className="licensor-modal-list">
          { Admin.filterSearchText(sortBy(this.state.options, this.props.property) as any[], this.state.searchText, this.props.property).map((option, index) => {
            return(
              <li key={ index } onClick={ this.props.func } data-id={ option.id }>{ option[this.props.property] }</li>
            );
          }) }
        </ul>
      </div>
    );
  }

  renderHeader() {
    if (this.props.header) {
      return(
        <h1>{ this.props.header }</h1>
      );
    } else {
      return null;
    }
  }
}

const mapStateToProps = (reducers, props) => {
  return reducers.standardReducer;
};

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchEntities }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(ModalSelect);
