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,
  icon: PropTypes.string.isRequired,
  isActive: PropTypes.bool,
  onClick: PropTypes.func,
  targetPanelLevel: PropTypes.number,
  targetPanelName: PropTypes.string,
  targetPanelTitle: PropTypes.node,
};

const defaultProps = {
  tag: 'a',
  defaultClassName: 'sui-o-secondary-nav__link',
  className: '',
  isActive: false,
  onClick: () => {},
  targetPanelLevel: 1,
  targetPanelName: '',
  targetPanelTitle: '',
};

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

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

    const {
      onHandlePanel,
    } = this.context;

    if (onClick) {
      onClick(e);
    }

    onHandlePanel(targetPanelLevel);
  }

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

    const classes = classnames(
      defaultClassName,
      className,
      {
        'as--active': isActive,
      }
    );

    if ((targetPanelLevel > 0) && (targetPanelName.length > 0)) {
      return (
        <>
          <Tag className={classes} {...attributes}>
            <span className="sui-o-secondary-nav__link-icon">
              <Icon name={icon} className="as--start" />
            </span>
            <span className="sui-o-secondary-nav__link-label">
              {children}
            </span>
          </Tag>
          <button type="button" href="#" className="sui-o-secondary-nav__link as--active" onClick={this.onClick}>
            <span className="sui-o-secondary-nav__link-label">
              {targetPanelTitle}
            </span>
            <span className="sui-o-secondary-nav__link-icon">
              <Icon name="arrow-right" className="as--end" />
            </span>
          </button>
        </>
      );
    }

    return (
      <Tag className={classes} {...attributes}>
        <span className="sui-o-secondary-nav__link-icon">
          <Icon name={icon} className="as--start" />
        </span>
        <span className="sui-o-secondary-nav__link-label">
          {children}
        </span>
      </Tag>
    );
  }
}

SecondaryNavLink.propTypes = propTypes;
SecondaryNavLink.defaultProps = defaultProps;
SecondaryNavLink.contextTypes = contextTypes;
