import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames/bind';
import ReactModal from 'react-modal';
import styles from './modal.scss';
import Closeable from '../Utilities/Closeable';
import Typography from '../Typography';
import Button from '../Button';

const Modal = ({
  children,
  visible,
  title,
  onConfirm,
  onCancel,
  confirm,
  buttons,
}) => {
  const cx = classnames.bind(styles);

  const [open, setOpen] = useState(visible);

  useEffect(() => {
    setOpen(visible);
  }, [visible]);

  return (
    <ReactModal
      isOpen={open}
      onRequestClose={onCancel}
      shouldCloseOnEsc
      shouldCloseOnOverlayClick
      className={cx('modal')}
      overlayClassName={cx('modal_overlay')}
    >
      <div
        className={cx('modal_top', {
          modal_top__title: title,
        })}
      >
        {title && <Typography.Title level={4}>{title}</Typography.Title>}

        <Closeable onClick={onCancel} />
      </div>

      <div className={cx('modal_content')}>{children}</div>

      {buttons && (
        <div className={cx('modal_buttons')}>
          {onConfirm && (
            <Button small onClick={onConfirm}>
              Oke
            </Button>
          )}
          {confirm}

          {onCancel && (
            <Button small theme="secondary" onClick={onCancel}>
              Annuleer
            </Button>
          )}
        </div>
      )}
    </ReactModal>
  );
};

Modal.defaultProps = {
  buttons: false,
  onConfirm: undefined,
  title: null,
  confirm: null,
};

Modal.propTypes = {
  buttons: PropTypes.bool,
  children: PropTypes.arrayOf(PropTypes.element).isRequired,
  confirm: PropTypes.element,
  onCancel: PropTypes.func.isRequired,
  onConfirm: PropTypes.func,
  title: PropTypes.string,
  visible: PropTypes.bool.isRequired,
};

export default Modal;
