import { CSSProperties, useEffect, useMemo, useRef } from 'react';
import { Dropdown, Menu } from 'antd';
import React from 'react';

function usePrevious(value) {
    const ref = useRef();
    useEffect(() => {
        ref.current = value;
    });
    return ref.current;
}

export default function ContextMenuVisible(options) {
    const {
        items,
        data,
        visible,
        onVisibleChange = () => undefined,
        pageX,
        pageY,
    } = options;
    const prevPageX = usePrevious(pageX);
    const prevPageY = usePrevious(pageY);

    const left = (pageX || prevPageX || 0);
    const top = (pageY || prevPageY || 0);

    const menu = useMemo(() => {
        return getOverlayMenu({
            items,
            data,
            onVisibleChange,
        });
    }, [ data, items, onVisibleChange ]);

    const style: CSSProperties = {
        position: 'fixed',
        zIndex: 999,
        width: 2,
        height: 2,
        transform: 'translate(-50%, -50%)',
        top,
        left,
        display: visible ? 'block' : 'none',
    };

    return (
        <Dropdown
            trigger={[ 'click' ]}
            visible={visible}
            overlay={menu || <div />}
            onVisibleChange={onVisibleChange}
            // @ts-ignore
            destroyPopupOnHide
        >
            <div style={style} />
        </Dropdown>
    );
}

function getOverlayMenu(options) {
    const {
        items = [],
        onVisibleChange = () => undefined,
        data,
    } = options;

    return (
        <Menu
            onClick={() => onVisibleChange(false)}
            // @ts-ignore
            items={items.map(item => {
                const loop = it => {
                    if (it.type) return it;
                    const _item = typeof it === 'function' ? it(data) : it;

                    const { key, label, icon, onClick, children, ...others } = _item;
                    const _key = key || label;
                    return {
                        ...others,
                        key: _key,
                        onClick: e => {
                            const { domEvent } = e;
                            domEvent.stopPropagation();
                            domEvent.preventDefault();

                            if (onClick) onClick(e, data);
                        },
                        icon,
                        label: <span style={{ display: 'inline-block', minWidth: 150 }}>{label}</span>,
                        children: children && children.map(loop),
                    };
                };
                return loop(item);
            })}
        />
    );

}
