import React, { PropTypes } from 'react';
import { typeOptions } from './optionsValue';

export default function MainSelector({ value, options, onChange }) {
  const buildOption = option => (
    <option key={option.value} value={option.value}>{option.label}</option>
  );
  const findLabel = key => typeOptions.find(option => option.value === key).label;

  const customGroupedOptions = options.custom.reduce((groups, option) => {
    const { entityType } = option;
    const group = groups[entityType] || [];

    return Object.assign({}, groups, { [entityType]: [...group, option] });
  }
  , {});

  const compOptions = options.first
    .map(buildOption)
    .concat(
      Object.keys(customGroupedOptions).map(key => (
        <optgroup key={key} label={findLabel(key)}>
          {customGroupedOptions[key].map(buildOption)}
        </optgroup>
      ))
    )
    .concat(
      options.last
        .map(buildOption),
    );

  return (
    <div className="c-base-select">
      <select onChange={evt => onChange(evt.target.value)} value={value}>
        {compOptions}
      </select>
    </div>
  );
}

MainSelector.propTypes = {
  theme: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.func,
  ]).isRequired,
  onChange: PropTypes.func,
  options: PropTypes.shape({}),
};
