import React, { useCallback, useState } from 'react';
import { Wrapper, DrawerWrap, DefaultSize, CloseWrap, Close } from './style';
import { IDrawer } from './types';
import { useKeyDown, usePrevious } from 'utils/hooks';
import { useSpring } from 'react-spring';
import ReactDom from 'react-dom';
import { mountContainer } from 'utils';

const mount = mountContainer('kwaiDrawerMount');

export const Drawer = function({ onCancel, onOk, children, visible, style, size, ...rest }: IDrawer) {
    const [delayVisible, setDelayVisible] = useState(false);
    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 values: any = {
        opacity: visible ? 1 : 0,
        onRest: (item: any) => {
            setDelayVisible(!!item.opacity);
        },
        config: { mass: 15, friction: 280, tension: 3000, clamp: true },
    };
    switch (rest.placement) {
        case 'top':
        case 'bottom':
            values.height = visible ? size : 0;
            break;
        case 'right':
        case 'left':
            values.width = visible ? size : 0;
            break;
    }
    const drawerStyle = useSpring(values);
    const drawer = (
        <Wrapper visible={visible || delayVisible} onClick={onCancel} style={wrapStyle} {...rest}>
            <DrawerWrap
                placement={rest.placement}
                onClick={(e: any) => e.stopPropagation()}
                size={size}
                style={{ ...style, ...drawerStyle }}
                className="drawer-body"
            >
                <CloseWrap placement={rest.placement}>
                    <Close
                        onClick={(e: any) => {
                            e.stopPropagation();
                            onCancel && onCancel();
                        }}
                    />
                </CloseWrap>
                {children}
            </DrawerWrap>
        </Wrapper>
    );

    return ReactDom.createPortal(drawer, mount);
};
Drawer.defaultProps = {
    placement: 'right',
    size: DefaultSize,
    dimBackground: true,
};
export default React.memo(Drawer);
