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

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

const StyledError = styled('div', {
    color: '$error-1',
    display: 'block',
    fontSize: '$xs',
    variants: {
        nowrap: {
            true: {
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
            },
        },
    },
    defaultVariants: {
        nowrap: true,
    },
});

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

/**
 * FormError component
 */
const _FormError = (
    props: FormErrorProps,
    ref: ForwardedRef<HTMLDivElement>,
): JSX.Element => {
    const { children, ...otherProps } = props;

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

export const FormError = forwardRef(_FormError) as (
    props: FormErrorProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _FormError>;
