import React, { PureComponent } from 'react';
import classNames from 'classnames';
import enhanceWithClickOutside from 'react-click-outside';

import '../base';
import styles from './NavigationUserDropdown.styl';

import Menu from '../atoms/Menu';
import NavigationUserInfo from './NavigationUserInfo';
import MediaQuery from '../atoms/MediaQuery';

class NavigationUserDropdown extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      open: props.open || false
    };

    this.toggleOpen = this.toggleOpen.bind(this);
  }

  toggleOpen(state) {
    this.setState({ open: typeof state === 'boolean' ? state : !this.state.open });
  }

  handleClickOutside() {
    this.toggleOpen(false);
  }

  render() {
    const { children, style, noMargin, ...props } = this.props;
    const { open } = this.state;

    const classes = classNames({
      [styles.dropdown]: true
    });

    return (
      <div className={classes} style={style}>
        <NavigationUserInfo {...props} noMargin={noMargin} onClick={this.toggleOpen} />
        <MediaQuery smallerThan small>
          <Menu primary open={open} triangle shadow style={{ position: 'fixed', right: 0, width: '100%' }}>
            {children}
          </Menu>
        </MediaQuery>
        <MediaQuery small>
          <Menu primary open={open} triangle shadow style={{ position: 'absolute', right: noMargin ? -9 : -58, width: 250 }}>
            {children}
          </Menu>
        </MediaQuery>
      </div>
    );
  }
}

export default enhanceWithClickOutside(NavigationUserDropdown);
