import React, { useState, useCallback, useRef } from 'react';
import { useSpring, animated } from 'react-spring';
import { Wrapper, Content, Message, Description, AlertIcon, CloseButton, CloseIcon } from './style';
import { IAlert } from './types';

function useHeight(): [(node: any) => void, number] {
    const [height, setHeight] = useState<number>(0);
    const measuredRef = useCallback(node => {
        if (node !== null) {
            setHeight(node.getBoundingClientRect().height);
        }
    }, []);
    return [measuredRef, height];
}

export const Alert: React.FC<IAlert> = ({
    type = 'info',
    message,
    closable = false,
    closeText,
    description,
    showIcon = false,
    icon,
    onClose,
    afterClose,
    children,
}) => {
    const parentRef = useRef<any>(null);
    const [v, setV] = useState<boolean>(true);
    const [measuredRef, viewHeight] = useHeight();
    const handleClose = useCallback((e: any) => {
        setV(false);
        onClose && onClose(e);
    }, []);
    const { height, opacity } = useSpring({
        opacity: v ? 1 : 0,
        height: v ? viewHeight : 0,
        config: { clamp: true },
        onRest: (e: any) => {
            if (!v && !e.height) {
                afterClose && afterClose();
                parentRef.current.parentNode.removeChild(parentRef.current);
            }
        },
    });

    return (
        <animated.div style={{ height, opacity }} ref={parentRef}>
            <Wrapper type={type} hasdesc={description} ref={measuredRef}>
                {showIcon ? icon ? icon : <AlertIcon type={type} hasdesc={description} className="alert-icon" /> : null}
                <Content hasdesc={description}>
                    {children ? (
                        children
                    ) : (
                        <>
                            <Message hasdesc={description}>{message}</Message>
                            <Description hasdesc={description}>{description}</Description>
                        </>
                    )}
                </Content>
                {closable ? (
                    <CloseButton onClick={handleClose}>{closeText ? closeText : <CloseIcon />}</CloseButton>
                ) : null}
            </Wrapper>
        </animated.div>
    );
};
Alert.defaultProps = {};
export default Alert;
