import * as React from 'react'
import {
    useFloating,
    autoUpdate,
    hide,
    offset,
    shift,
} from '@floating-ui/react-dom'
import { useMergeRefs, isTestEnvironment } from '@planview/pv-utilities'
import { Portal } from '@planview/pv-uikit'
import { AnchoredContainer, AnchoredContainerPortal } from './styles'

export const AnchoredPortal = React.forwardRef<
    HTMLDivElement,
    {
        children: React.ReactNode
        minWidth: number
        onHidden: () => void
        onKeyDown: (ev: React.KeyboardEvent<HTMLDivElement>) => void
    }
>(function AnchoredPortal(
    { children, minWidth, onHidden, onKeyDown },
    containerRef
) {
    const {
        refs: { setFloating, setReference },
        x,
        y,
        strategy,
        middlewareData,
    } = useFloating({
        placement: 'left-start',
        middleware: [
            offset(({ rects }) => ({
                mainAxis: -rects.floating.width,
            })),
            shift({ crossAxis: true, padding: 8 }),
            isTestEnvironment ? null : hide(),
        ],
        whileElementsMounted: autoUpdate,
    })
    const floatingRef = useMergeRefs([containerRef, setFloating])
    const hidden = !!middlewareData.hide?.referenceHidden

    React.useEffect(() => {
        if (hidden) {
            onHidden()
        }
    }, [hidden, onHidden])

    return (
        <AnchoredContainer ref={setReference}>
            <Portal type="pvds-grid-editor">
                <AnchoredContainerPortal
                    ref={floatingRef}
                    onKeyDown={onKeyDown}
                    style={{
                        position: strategy,
                        top: y,
                        left: x,
                        minWidth: Math.max(minWidth, 250),
                        visibility: hidden ? 'hidden' : undefined,
                    }}
                >
                    {children}
                </AnchoredContainerPortal>
            </Portal>
        </AnchoredContainer>
    )
})
