import { ComponentPropsWithRef, forwardRef, ForwardedRef } from 'react';

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

const StyledLabel = styled('label', {
    color: '$grey-1',
    display: 'block',
    fontSize: '$sm',
    fontWeight: '$medium',
    variants: {
        nowrap: {
            true: {
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
            },
        },
        display: {
            flex: {
                display: 'inline-flex',
                margin: '0 $2 0 0',
            },
            inline: {
                margin: '0 0 $1 0',
            },
        },
    },
    defaultVariants: {
        nowrap: true,
    },
});

export interface FormLabelProps extends ComponentPropsWithRef<'label'> {
    /** Allow the label to wrap to the next line */
    nowrap?: boolean;
}

/**
 * Form Label component
 */
const _FormLabel = (
    props: FormLabelProps,
    ref: ForwardedRef<HTMLLabelElement>,
): JSX.Element => {
    const { children, ...otherProps } = props;

    return (
        <StyledLabel ref={ref} {...otherProps}>
            {children}
        </StyledLabel>
    );
};

export const FormLabel = forwardRef(_FormLabel) as (
    props: FormLabelProps & {
        ref?: ForwardedRef<HTMLLabelElement>;
    },
) => ReturnType<typeof _FormLabel>;
