import React, { useState, memo } from 'react';
import ReactDom from 'react-dom';
import { Wrapper, ModalWrap, FooterWrap, Title, Close } from './style';
import Button from '../button';
import { useSpring } from 'react-spring';
import { IModal } from './types';
import { useKeyDown, usePrevious } from 'utils/hooks';
import { mountContainer } from 'utils';

const mount = mountContainer('kwaiModalMount');

export const Modal = function({
    visible,
    onCancel,
    onOk,
    title,
    footer = (
        <>
            <Button onClick={onCancel} key="cancel" appearance="ghost">
                取消
            </Button>
            <Button key="ok" onClick={onOk}>
                确认
            </Button>
        </>
    ),
    footerAlign,
    children,
    width = 448,
    style: propStyle,
    ...rest
}: IModal) {
    const [delayVisible, setDelayVisible] = useState(false);
    //useLockBodyScroll(visible || delayVisible);

    const esc = useKeyDown('Escape');
    const stamp = usePrevious<number>(+new Date());
    if (esc && visible && onCancel && +new Date() - 10 > stamp!) {
        onCancel();
    }
    const wrapStyle = useSpring({
        opacity: visible ? 1 : 0,
        config: { mass: 5, friction: 180, tension: 3000, clamp: true },
    });
    const style = useSpring({
        opacity: visible ? 1 : 0,
        transform: `translate3d(0, -${visible ? 0 : 15}%, 0)`,
        onRest: (item: any) => {
            setDelayVisible(!!item.opacity);
        },
        config: { mass: 5, friction: 180, tension: 3000, clamp: true },
    });
    const modal = (
        <Wrapper visible={visible || delayVisible} onClick={onCancel} style={wrapStyle} {...rest}>
            <ModalWrap
                onClick={(e: any) => e.stopPropagation()}
                width={width}
                style={{ ...propStyle, ...style }}
                className="modal-body"
            >
                {title && <Title className="modal-title">{title}</Title>}
                <Close onClick={onCancel} />
                {children}
                <FooterWrap footerAlign={footerAlign}>{footer}</FooterWrap>
            </ModalWrap>
        </Wrapper>
    );

    return ReactDom.createPortal(modal, mount);
};
Modal.defaultProps = {
    footerAlign: 'right',
};
export default memo(Modal);
