import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import '../base';
import styles from './Radio.styl';
import newId from '../utils/newId';

export default class Radio extends React.Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }

  componentWillMount() {
    this.id = newId();
  }

  onClick(e) {
    if (this.context.readonly && this.context.toggleReadonly) this.context.toggleReadonly(e);
    if (this.props.onClick) this.props.onClick(e);
  }

  render() {
    const { label, ...rest } = this.props;
    const { readonly } = this.context;
    // We need a unique id for the link between input and label, even if the user doesn't provide one.
    const id = this.props.id || this.id;

    const wrapperClasses = classNames({
      [styles.input]: true,
      [styles.readonly]: readonly
    });

    return (
      <div className={styles.wrapper}>
        <input
          {...rest}
          type="radio"
          ref={(ref) => { this.input = ref; }}
          id={id}
          readOnly={readonly}
          onClick={this.onClick}
          className={wrapperClasses}
        />
        <label
          className={styles.label}
          htmlFor={id}
        >
          {label || ''}
        </label>
      </div>
    );
  }
}

Radio.propTypes = {
  checked: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  label: PropTypes.string
};

Radio.defaultProps = {
  checked: undefined,
  label: undefined
};

Radio.contextTypes = {
  readonly: PropTypes.bool,
  toggleReadonly: PropTypes.func
};
