import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { Icon } from '../../atoms/icon/Icon';

const propTypes = {
  actions: PropTypes.node,
  children: PropTypes.node,
  isPortalDisabled: PropTypes.bool,
  onClose: PropTypes.func,
  portalContainer: PropTypes.instanceOf(Element),
  selected: PropTypes.number,
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,
};

const defaultProps = {
  actions: [],
  children: null,
  isPortalDisabled: false,
  onClose: () => {},
  portalContainer: null,
  selected: 0,
  tag: 'div',
};

export const PagePopin = ({
  actions, children, isPortalDisabled, onClose, portalContainer, selected, tag: Tag,
}) => {
  const handleClose = () => {
    onClose();
  };

  const portalTarget = portalContainer || document.querySelector('.sui-l-app-layout__page');

  const popin = (
    <Tag className={`sui-o-page-popin ${selected > 0 ? 'as--open' : ''}`}>
      <div className="sui-o-page-popin__content">
        {children || `${selected} item${selected > 1 ? 's' : ''} selected`}
      </div>
      {actions}
      <div className="sui-o-page-popin__back">
        <button type="button" className="sui-o-page-popin__button as--square" onClick={handleClose}>
          <Icon name="close" />
        </button>
      </div>
    </Tag>
  );

  if (isPortalDisabled) {
    return popin;
  }

  return ReactDOM.createPortal(popin, portalTarget || document.body);
};

PagePopin.propTypes = propTypes;
PagePopin.defaultProps = defaultProps;
