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

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

const StyledPopoverContent = styled(Content, {
    backgroundColor: theme.colors.base,
    borderColor: theme.colors['grey-4'],
    borderWidth: theme.borderWidths.default,
    borderRadius: theme.radii.rounded,
    boxShadow: theme.shadows.default,
    outline: 'none',
    padding: theme.space['4'],
    zIndex: '30',
    '&:focus': {
        outline: `2px solid ${theme.colors['primary-1']}`,
        outlineOffset: '2px',
    },
});

export interface PopoverContentProps 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 popover to */
    container?: HTMLElement | null;
}

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

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

export const PopoverContent = forwardRef(_PopoverContent) as (
    props: PopoverContentProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _PopoverContent>;
