import React, { useEffect, useLayoutEffect, useState } from 'react';
import PropTypes from 'prop-types';
import Portal from '@material-ui/core/Portal';
import { withStyles } from '@material-ui/core/styles';

const styles = {
    root: {
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 1,
        pointerEvents: 'none',
        '& > *': {
            pointerEvents: 'all',
        },
    },
};

const InlineToolboxPortal = ({
    classes,
    canvasPosition,
    canvas,
    selectedObject,
    inlineToolboxRef,
    ...props
}) => {
    const [style, setStyle] = useState(null);
    useEffect(() => {
        const { top, left, width, height } = canvas.canvasElement.getBoundingClientRect();
        setStyle({ top, left, width, height, position: 'absolute' });
    }, [canvasPosition, canvas, selectedObject, inlineToolboxRef]);
    useLayoutEffect(() => {
        inlineToolboxRef && inlineToolboxRef.updateToolbarTransform();
    }, [style, inlineToolboxRef]);
    return (
        <Portal>
            <div className={classes.root} style={style} {...props} />
        </Portal>
    );
};

InlineToolboxPortal.propTypes = {
    classes: PropTypes.object.isRequired,
    canvasPosition: PropTypes.object.isRequired,
    canvas: PropTypes.object.isRequired,
    selectedObject: PropTypes.object,
    inlineToolboxRef: PropTypes.object,
};

export const StyledInlineToolboxPortal = withStyles(styles, { name: 'StandardToolboxPortal' })(
    InlineToolboxPortal
);

export default StyledInlineToolboxPortal;
