import React, { Component } from 'react';
import { hasClass } from '../lib/dom';

export default class Modal extends Component {
  constructor(props) {
    super(props);
  }

  backdropClicked(e) {
    if (hasClass(e.target, 'acms-admin-modal')) {
      this.props.onClose();
    }
  }

  componentDidUpdate() {
    if (this.props.lastFocus) {
      const buttons = this.modal.querySelectorAll('button');
      if (buttons && buttons.length) {
        buttons[buttons.length - 1].focus();
      }
    } else {
      this.closeBtn.focus();
    }
  }

  render() {
    const {
      children, isOpen, onClose, style, footer, title
    } = this.props;
    const display = isOpen ? 'block' : 'none';

    return (
      <div // eslint-disable-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions
        className="acms-admin-modal display"
        style={Object.assign({}, style, { display })}
        onClick={this.backdropClicked.bind(this)}
        role="dialog"
        ref={(modal) => { this.modal = modal; }}
      >
        <div className="acms-admin-modal-dialog">
          <div className="acms-admin-modal-content">
            <div className="acms-admin-modal-header">
              <button className="acms-admin-modal-hide acms-admin-icon-delete" onClick={onClose} ref={(closeBtn) => { this.closeBtn = closeBtn; }} />
              {title}
            </div>
            <div className="acms-admin-modal-body">
              {children}
            </div>
            <div className="acms-admin-modal-footer">
              {footer}
            </div>
          </div>
        </div>
      </div>
    );
  }
}
