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

// Style
/* istanbul ignore next */
if (typeof window !== 'undefined') require('./style.scss');

class Dropdown extends React.Component {
  static propTypes = {
    align: PropTypes.oneOf(['start', 'top', 'center', 'bottom', 'end']),
    className: PropTypes.string,
    justify: PropTypes.oneOf(['start', 'left', 'center', 'right', 'end']),
    onToggle: PropTypes.func,
    open: PropTypes.bool,
    sticky: PropTypes.bool,
    trigger: PropTypes.oneOf(['click', 'hover']),
  };

  static defaultProps = {
    align: 'start',
    justify: 'start',
    open: false,
    sticky: false,
    trigger: 'click',
  };

  constructor(props) {
    super(props);
    this.state = {
      open: props.open || false,
    };
    this.toggle = this.toggle.bind(this);
  }

  toggle = val => {
    const value = [true, false].includes(val) ? val : !this.state.open;
    this.setState({ open: value });
    if (typeof this.props.onToggle === 'function') this.props.onToggle(value);
  };

  render() {
    const { align, className, justify, children, sticky, trigger } = this.props;
    const clickEvents = { ...(trigger === 'click' && { onClick: this.toggle }) };
    const hoverEvents = {
      ...(trigger === 'hover' && { onMouseEnter: e => this.toggle(e, true), onClick: this.toggle }),
    };
    const [button = 'Toggle', ...content] = Array.isArray(children) ? children : [undefined, children];
    const DropdownClasses = [
      className,
      'Dropdown',
      `Dropdown_align=${align}`,
      `Dropdown_justify=${justify}`,
      `Dropdown_${this.state.open ? 'opened' : 'closed'}`,
    ]
      .filter(e => e)
      .join(' ');
    return (
      <div
        {...hoverEvents}
        className={DropdownClasses}
        onMouseLeave={() => !sticky && this.toggle(false)}
        style={this.props.style}
      >
        <div {...clickEvents} className="Dropdown-toggle">
          {button}
        </div>
        <div className={`Dropdown-content Dropdown-content_${this.state.open ? 'opened' : 'closed'}`}>{content}</div>
      </div>
    );
  }
}

export default Dropdown;
