import classNames from 'classnames';
import React, { PropTypes } from 'react';

function BaseSelect({ options, onChange, defaultValue, theme }) {
  const buildOption = option => (
    <option
      value={option.id}
      key={option.id}
    >
      {option.displayName}
    </option>
  );

  const sortBy = (x, y) => {
    if (x.position < y.position) {
      return -1;
    }
    if (x.position > y.position) {
      return 1;
    }
    return 0;
  };
  return (
    <div
      className={
        classNames(
          'c-base-select',
          theme['c-base-select'],
        )
      }
    >
      <select key={defaultValue} onChange={onChange} defaultValue={defaultValue}>
        {options.sort(sortBy).map(buildOption)}
      </select>
    </div>
  );
}

BaseSelect.propTypes = {
  theme: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.func,
  ]).isRequired,
  onChange: PropTypes.func,
  defaultValue: PropTypes.string,
  options: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string,
      displayName: PropTypes.string,
    })
  ),
};

export default BaseSelect;
