import * as React from "react";
import * as ReactDOM from 'react-dom';
import {Fragment} from "react";
import sc from 'utils/classname'
import Button from "../button";
import './index.scss';
import Icon from "../icon/icon";

interface IProps {
  visible: boolean,
  title?: string,
  width?: string,
  className?: string,
  onOk?: React.MouseEventHandler,
  onCancel?: React.MouseEventHandler,
}

export const Modal: React.FunctionComponent<IProps> = (props) => {
  const {
    visible,
    className,
    title,
    children,
    onCancel,
    onOk
  } = props;

  let width = '560px';  // default modal width
  if (props.width) {
    width = Number.isInteger(+props.width) ? props.width + 'px' : props.width;
  }

  const onClickOk: React.MouseEventHandler = (e) => {
    onOk && onOk(e);
  };

  const onClickCancel: React.MouseEventHandler = (e) => {
    onCancel && onCancel(e);
  };

  const renderModal = visible ?
    <Fragment>
      <div className="wen-modal-mask"/>
      <div className={sc('wen-modal', className)}
           style={{width: width}}>
        <Icon
          className="wen-modal-close-icon"
          name="close"
          onClick={onCancel}
        />
        <div className="wen-modal-head">
          {title}
        </div>
        <div className="wen-modal-body">
          {children}
        </div>
        <div className="wen-modal-footer">
          <Button
            className="wen-modal-ok-button"
            type="primary"
            onClick={onClickOk}
          >
            确认
          </Button>
          <Button
            className="wen-modal-cancel-button"
            type="danger"
            onClick={onClickCancel}
          >
            取消
          </Button>
        </div>
      </div>
    </Fragment> :
    null;

  return ReactDOM.createPortal(renderModal, document.body);
};


Modal.defaultProps = {
  title: 'Modal title',
  visible: false
};

export default Modal;


