import React from "react";
import { connect } from "redux-bundler-react";
import ErrorBoundary from "../utils/error-boundary";

class PrimaryPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      left: 49,
    };
    this.handleResize = this.handleResize.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }

  handleResize(e) {
    e.preventDefault();
    e.stopPropagation();
    let { left } = this.state;

    if (e.pageX) {
      this.props.doPrimaryPanelSetWidth(e.pageX - left);
    }
  }

  handleClose(e) {
    e.preventDefault();
    e.stopPropagation();
    this.props.doPrimaryPanelClose();
  }

  render() {
    const {
      primaryPanelChildren,
      primaryPanelOptions,
      primaryPanelTop,
      primaryPanelShowClose,
      primaryPanelWidth,
    } = this.props;
    const { left, width } = this.state;

    if (!primaryPanelChildren || !primaryPanelChildren.length) return null;

    return (
      <div
        className="sidebar-panel"
        style={{ top: primaryPanelTop, left: left, width: primaryPanelWidth }}
      >
        <ErrorBoundary>
          <div id="primary-panel-content">
            {primaryPanelShowClose ? (
              <div className="row">
                <button
                  className="pull-right cm-btn cm-btn-link"
                  title="Close Panel "
                  style={{ marginRight: "10px", padding: "3px" }}
                  onClick={this.handleClose}
                >
                  <i
                    className="mdi mdi-close-circle-outline"
                    style={{ fontSize: "22px" }}
                  />
                </button>
              </div>
            ) : null}

            {primaryPanelChildren.map((component, i) => {
              const Comp = component;
              return <Comp key={i} {...primaryPanelOptions} />;
            })}
          </div>
        </ErrorBoundary>

        <div
          className="e-w-drag-handle"
          draggable="true"
          onDrag={this.handleResize}
          onDragEnd={this.handleResize}
        />
      </div>
    );
  }
}

export default connect(
  "selectPrimaryPanelTop",
  "selectPrimaryPanelChildren",
  "selectPrimaryPanelOptions",
  "selectPrimaryPanelWidth",
  "selectPrimaryPanelShowClose",
  "doPrimaryPanelResize",
  "doPrimaryPanelSetWidth",
  "doPrimaryPanelClose",
  PrimaryPanel
);
