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

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

export default class Checkbox 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);
  }

  blur() {
    if (this.input) {
      this.input.blur();
    }
  }

  focus() {
    if (this.input) {
      this.input.focus();
    }
  }

  render() {
    const { label, partial, ...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.wrapper]: true,
      [styles.readonly]: readonly,
      [styles.partial]: partial
    });

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

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

Checkbox.defaultProps = {
  checked: undefined,
  label: undefined,
  partial: undefined
};

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