/* eslint prefer-const: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { dropUnwantedProps } from '../../../helpers';
import { Icon } from '../../atoms/icon/Icon';

const propTypes = {
  children: PropTypes.node.isRequired,
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  className: PropTypes.string,
  onClick: PropTypes.func,
  isButton: PropTypes.bool,
  targetPanelLevel: PropTypes.number,
};

const defaultProps = {
  tag: 'a',
  defaultClassName: 'sui-o-secondary-nav__back',
  className: '',
  onClick: () => {},
  isButton: false,
  targetPanelLevel: 0,
};

const contextTypes = {
  onHandlePanel: PropTypes.func,
};

export class SecondaryNavBackButton extends React.Component {
  onClick = (e) => {
    const {
      onClick,
      targetPanelLevel,
    } = this.props;

    const {
      onHandlePanel,
    } = this.context;

    if (targetPanelLevel < 1) {
      return;
    }

    if (onClick) {
      onClick(e);
    }

    onHandlePanel(targetPanelLevel);
  };

  render() {
    let {
      children,
      tag: Tag,
      defaultClassName,
      className,
      isButton,
      targetPanelLevel,
      ...attributes
    } = dropUnwantedProps(this.props, ['onClick', 'targetPanelName']);

    const classes = classnames(
      className,
      isButton || targetPanelLevel ? 'sui-o-secondary-nav__back' : defaultClassName,
    );

    return (
      <Tag className={classes} {...attributes} onClick={this.onClick}>
        <span className="sui-o-secondary-nav__back-icon">
          <Icon name="arrow-left" />
        </span>
        {children}
      </Tag>
    );
  }
}

SecondaryNavBackButton.propTypes = propTypes;
SecondaryNavBackButton.defaultProps = defaultProps;
SecondaryNavBackButton.contextTypes = contextTypes;
