import React from 'react';
import PropTypes from 'prop-types';
import omit from 'lodash/omit';

import FieldControl from '../FieldControl';
import './radio.scss';

function getInputProps(props) {
  const { input, ...resultProps } = props;
  return { ...resultProps, ...input };
}

class Radio extends React.Component {
  static propTypes = {
    disabled: PropTypes.bool,
    options: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
    value: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number,
      PropTypes.bool,
      PropTypes.array,
      PropTypes.object
    ]),
    onChange: PropTypes.func,
    input: PropTypes.object
  };

  static defaultProps = {
    disabled: false,
    options: [],
    value: null,
    onChange: null,
    input: null
  };

  handleOnChange = value => () => {
    const { onChange } = this.props.input || this.props;
    if (typeof onChange === 'function') {
      onChange(value);
    }
  };

  render() {
    const {
      options,
      ...props
    } = this.props;

    const parsedOptions = Array.isArray(options) ? options
      : Object.keys(options).map(key => ({ label: key, value: options[key] }));
    const { _mountOrder, _rootNodeID } = this._reactInternalInstance;

    return (
      <FieldControl {...props}>
        {restProps => {
          const {
            value,
            disabled,
            ...resultProps
          } = getInputProps(restProps);
          return parsedOptions.map(({ value: optionValue, label: optionLabel, disabled: optionDisabled }) =>
            <div styleName="radio" key={optionValue}>
              <label htmlFor={`_${_rootNodeID}-${_mountOrder}-${optionValue}`}>
                <input
                  id={`_${_rootNodeID}-${_mountOrder}-${optionValue}`}
                  type="radio"
                  value={optionValue}
                  checked={JSON.stringify(value) === JSON.stringify(optionValue)}
                  onChange={this.handleOnChange(optionValue)}
                  disabled={disabled || optionDisabled}
                  {...omit(resultProps, ['onChange'])}
                />
                {optionLabel}
              </label>
            </div>
          );
        }}
      </FieldControl>
    );
  }
}

export default Radio;
