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

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

const StyledDropdownContent = styled(Content, {
    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 DropdownContentProps extends ComponentPropsWithRef<'div'> {
    /** Content to display in the popover */
    children: ReactNode;

    /** Side where the content is position (relative to the trigger)  */
    side?: 'top' | 'right' | 'bottom' | 'left';

    /** Pixel distance the popover is away from the side  */
    offset?: number;

    /** Alignment of the content (relative to the trigger)  */
    align?: 'start' | 'center' | 'end';

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

/**
 * DropdownContent component
 */
const _DropdownContent = (
    props: DropdownContentProps,
    ref: ForwardedRef<HTMLDivElement>,
): JSX.Element => {
    const {
        children,
        side,
        offset = 4,
        align,
        container,
        ...otherProps
    } = props;

    return (
        <Portal container={container}>
            <StyledDropdownContent
                sideOffset={offset}
                ref={ref}
                side={side}
                align={align}
                {...otherProps}
            >
                {children}
            </StyledDropdownContent>
        </Portal>
    );
};

export const DropdownContent = forwardRef(_DropdownContent) as (
    props: DropdownContentProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _DropdownContent>;
