import React from 'react';
import PropTypes from 'prop-types';
import omit from 'lodash/omit';
import classNames from 'classnames';
import FieldControl from '../FieldControl/index';

import './checkbox.scss';

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

const propTypes = {
  optionValue: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.bool,
    PropTypes.array,
    PropTypes.object
  ]),
  children: PropTypes.node,
  input: PropTypes.object,
  variant: PropTypes.oneOf(['toggle-switch'])
};

const defaultProps = {
  input: null,
  children: null,
  variant: undefined,
  optionValue: true
};

class CheckBox extends React.Component {
  onChange = event => {
    const { onChange, optionValue } = getInputProps(this.props);
    const { target: { checked } } = event;
    if (typeof onChange === 'function') {
      onChange(checked ? optionValue : false, optionValue);
    }
  };

  onBlur = event => {
    const { onBlur, optionValue } = getInputProps(this.props);
    const { target: { checked } } = event;
    if (typeof onBlur === 'function') {
      onBlur(checked ? optionValue : false, optionValue);
    }
  }

  render() {
    const {
      children,
      variant,
      ...props
    } = this.props;
    const { _mountOrder, _rootNodeID } = this._reactInternalInstance;

    return (
      <FieldControl {...props}>
        {restProps => {
          const resultProps = omit(getInputProps(restProps), ['id', 'type', 'checked',
            'onChange', 'optionValue', 'onBlur']);
          return (
            <div styleName={classNames('base', variant)}>
              <input
                id={`_${_rootNodeID}-${_mountOrder}`}
                type="checkbox"
                onChange={this.onChange}
                onBlur={this.onBlur}
                checked={resultProps.value !== false && resultProps.value !== '' && resultProps.value !== undefined}
                {...resultProps}
              />
              <label htmlFor={`_${_rootNodeID}-${_mountOrder}`}>
                {children}
              </label>
            </div>
          );
        }}
      </FieldControl>
    );
  }
}

CheckBox.propTypes = propTypes;
CheckBox.defaultProps = defaultProps;
export default CheckBox;
