import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import Icon from 'amos-icon';
import classnames from 'classnames';
import { omit } from 'amos-tool';
import { Animate } from 'amos-framework';

/**
 * common panel enhance
 * @param {React.Node} WrapperCompontent
 * @param {object} option
 */
export default function commonPane(WrapperCompontent, option) {

  const {
    wrapperClassName
  } = option || {};

  class ContentPanelComponent extends Component {

    static propTypes = {
      children: PropTypes.node,
      title: PropTypes.string,
      titleIcon: PropTypes.string,
      showClose: PropTypes.bool,
      onClose: PropTypes.func,
      secondContent: PropTypes.array
    }

    static defaultProps = {
      showClose: true,
      secondContent: []
    }

    constructor(props) {
      super(props);

    }

    removeContainer = () => {
      if (this._container) {
        const container = this._container;
        ReactDOM.unmountComponentAtNode(container.parentNode);
        this._container = null;

        if (this.props.onClose){
          this.props.onClose();
        }
      }
    }

    render() {
      const { titleIcon, showClose, title, ...rest } = this.props;
      const wrapperCls = classnames('common-panel-wrapper', {
        [wrapperClassName]: !!wrapperClassName
      });

      const newRest = omit(rest, ['onClose']);

      return (
        <Animate
          key="common-panel"
          transitionName="slide-down"
          transitionAppear
        >
          <div className={wrapperCls} ref={node => this._container = node}>
            <div className="common-panel-title-bar">
              <div className="common-panel-title">
                { titleIcon && <Icon className="" icon={titleIcon} /> }
                { title && <span>{title}</span>}
              </div>
              {showClose && <Icon className="common-panel-close-icon" onClick={this.removeContainer} icon="close" />}
            </div>
            <div className="common-panel-contanier">
              <div className="common-panel-content">
                <WrapperCompontent removeContainer={this.removeContainer} {...newRest} />
              </div>
            </div>
          </div>
        </Animate>
      );
    }
  }

  return ContentPanelComponent;
}
