import * as React from 'react';
import * as ReactDOM from 'react-dom';

import { ModalStyle, Close, WrapperButton, Overlay } from './Modal.styled';
import { Button, Icons } from '../index';

interface IProps {
  active: boolean;
  type?: string;
  onClose: (boolean: boolean) => void;
  onConfirm?: () => void|any;
  onConfirmText?: string;
  selector: string;
}

export default class Modal extends React.PureComponent<IProps> {
  el: HTMLElement | Node | null;
  state = {
    animation: 'enter',
  };

  componentDidMount() {
    this.el = document.querySelector(this.props.selector);
  }

  onClose = async () => {
    this.setState({ animation: 'leave' });
    setTimeout(() => {
      this.props.onClose(false);
      this.setState({ animation: 'enter' });
    }, 400);
  }

  onConfirm = () => this.props.onConfirm && this.props.onConfirm();

  render () {
    const { active, children, type, onConfirm, onConfirmText } = this.props;
    const isType = type || 'default';

    return active && ReactDOM.createPortal((
      <React.Fragment>
        { isType !== 'full' && <Overlay animation={this.state.animation} onClick={this.onClose} />}
        <ModalStyle animation={this.state.animation} type={isType}>
          <Close type='button' onClick={this.onClose} isType={isType}>
            <Icons.Close width={27} height={27} />
          </Close>
          <div>{children}</div>
          {
            isType !== 'small' && (
              <WrapperButton>
                <Button isType='link' type='button' onClick={this.onClose}>FECHAR</Button>
                {onConfirm && <Button isType='confirm' type='button' onClick={this.onConfirm}>{onConfirmText || 'Salvar'}</Button>}
              </WrapperButton>
            )
          }
        </ModalStyle>
      </React.Fragment>
    ), (this.el as HTMLElement))
  }
}
