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

import '../base';
import Icon from './Icon';
import styles from './Select.styl';
import newId from '../utils/newId';
import Label from './Label';
import labelStyles from './Label.styl';


export default class Select extends React.Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
    this.onFocus = this.onFocus.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);
  }

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

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

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

  render() {
    const { type, label, error, success, warning, info, children, ...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.error]: !!error,
      [styles.error]: !!error,
      [styles.warning]: !!warning,
      [styles.info]: !!info,
      [styles.success]: !!success,
      [styles.labelOffset]: !!label
    });

    const inputLabelText = label;

    return (
      <div className={wrapperClasses}>
        <select
          {...rest}
          type={type || 'text'}
          ref={(ref) => { this.input = ref; }}
          id={id}
          onClick={this.onClick}
          onFocus={this.onFocus}
          className={`${styles.select} ${labelStyles.input}`}
        >
          {children}
        </select>
        {!!inputLabelText && (
          <Label
            htmlFor={id}
            {...{ error, warning, info, success }}
          >
            {inputLabelText}
          </Label>
        )}
        <Icon name="doka-icon-dropdown" className={styles.icon} />
      </div>
    );
  }
}

Select.propTypes = {
  children: PropTypes.node,
  type: PropTypes.string,
  label: PropTypes.string,
  error: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.bool
  ]),
  warning: PropTypes.bool,
  info: PropTypes.bool,
  success: PropTypes.bool
};

Select.defaultProps = {
  children: undefined,
  type: undefined,
  label: undefined,
  error: undefined,
  warning: undefined,
  info: undefined,
  success: undefined
};

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