import {
    ComponentPropsWithRef,
    ReactNode,
    forwardRef,
    ForwardedRef,
} from 'react';
import { SubContent } from '@radix-ui/react-dropdown-menu';
import { Portal } from '../Portal';

import { styled, theme } from '../../stitches.config';

const StyledDropdownSubMenuContent = styled(SubContent, {
    minWidth: theme.space['56'],
    backgroundColor: theme.colors.base,
    borderColor: theme.colors['grey-4'],
    borderWidth: theme.borderWidths.default,
    borderRadius: theme.radii.default,
    boxShadow: theme.shadows.default,
    padding: theme.space['1'],
    zIndex: '30',
});

export interface DropdownSubMenuContentProps
    extends ComponentPropsWithRef<'div'> {
    /** Content to display in the popover */
    children: ReactNode;

    /** Container to append the dropdown to */
    container?: HTMLElement | null;
}

/**
 * DropdownSubMenuContent component
 */
const _DropdownSubMenuContent = (
    props: DropdownSubMenuContentProps,
    ref: ForwardedRef<HTMLDivElement>,
): JSX.Element => {
    const { children, container, ...otherProps } = props;

    return (
        <Portal container={container}>
            <StyledDropdownSubMenuContent
                alignOffset={-4}
                sideOffset={-4}
                ref={ref}
                {...otherProps}
            >
                {children}
            </StyledDropdownSubMenuContent>
        </Portal>
    );
};

export const DropdownSubMenuContent = forwardRef(_DropdownSubMenuContent) as (
    props: DropdownSubMenuContentProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _DropdownSubMenuContent>;
