import React, { useState, useImperativeHandle } from 'react';
import Popup from './popup';
import ReactDom from 'react-dom';
export const mountContainer = (ref: any) => {
    let kwaiPopoverMount = document.getElementById('kwaiPopoverMount');
    if (!kwaiPopoverMount) {
        document.body.insertAdjacentHTML(
            'beforeend',
            '<div id="kwaiPopoverMount" style="position: absolute; top: 0; left: 0; width: 100%;"></div>'
        );
        kwaiPopoverMount = document.getElementById('kwaiPopoverMount') as HTMLElement;
    }
    ReactDom.render(<PopupHub ref={ref} />, kwaiPopoverMount);
};

//export const mountPopup = (props: IProps) => {
//    console.log(props);
//    const ref = useRef();
//    const container = mountContainer();
//    const popupContainer = document.createElement('div');
//    container.appendChild(popupContainer);
//    ReactDom.render(<Popup {...props} ref={ref} />, popupContainer);
//    return ref;
//};

export const getSiblingLocation = (ref: any) => {
    const child = ref.current ? ref.current.previousElementSibling : document.body;
    return getNodeAbsolutePosition(child as HTMLElement);
};

export function getNodeAbsolutePosition(element: HTMLElement) {
    const rect = element.getBoundingClientRect();
    const bodyRect = document.body.getBoundingClientRect();
    return {
        width: rect.width,
        height: rect.height,
        left: rect.left - bodyRect.left,
        top: rect.top - bodyRect.top,
        right: bodyRect.right - rect.right,
        bottom: bodyRect.bottom - rect.bottom - bodyRect.height,
    };
}

const PopupHub = React.forwardRef(function(props, ref) {
    const [popups, setPopups] = useState([]);
    useImperativeHandle(ref, () => ({ setPopups, popups }));
    return (
        <>
            {popups.map(({ uid, ...rest }: any) => (
                <Popup {...rest} key={uid} />
            ))}
        </>
    );
});
