import { ReactNode, forwardRef, ForwardedRef } from 'react';
import { Overlay, Content, Portal } from '@radix-ui/react-dialog';

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

const StyledOverlay = styled(Overlay, {
    backgroundColor: '$transparent-dark-4',
    position: 'fixed',
    inset: 0,
    zIndex: '10',
});

const StyledContent = styled(Content, {
    backgroundColor: '$base',
    borderRadius: '$default',
    boxShadow: '$default',
    position: 'fixed',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: '100%',
    maxHeight: '85vh',
    padding: '$6 $2 $6 $2',
    display: 'flex',
    flexDirection: 'column',
    zIndex: '20',
    variants: {
        size: {
            sm: {
                maxWidth: '22.5rem',
            },
            md: {
                maxWidth: '32.5rem',
            },
            lg: {
                maxWidth: '45rem',
            },
        },
    },
});

export interface ModalContentProps {
    /** Container for the modal's content */
    container?: HTMLElement;

    /** Content to act as the modal's content */
    children: ReactNode;

    /** Size of the modal's content */
    size?: 'sm' | 'md' | 'lg';
}

/**
 * ModalContent Component
 */
const _ModalContent = (
    props: ModalContentProps,
    ref: ForwardedRef<HTMLDivElement>,
): JSX.Element => {
    const { container, children, size = 'md', ...otherProps } = props;

    return (
        <Portal container={container}>
            <StyledOverlay />
            <StyledContent ref={ref} size={size} {...otherProps}>
                {children}
            </StyledContent>
        </Portal>
    );
};

export const ModalContent = forwardRef(_ModalContent) as (
    props: ModalContentProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _ModalContent>;
