import { ComponentPropsWithRef, ForwardedRef, forwardRef } from 'react';
import { styled, theme } from '../../stitches.config';

import { Icon } from '../Icon';
import { IconButton, IconButtonProps } from '../IconButton';

const StyledPill = styled('div', {
    display: 'inline-flex',
    alignItems: 'center',
    whiteSpace: 'nowrap',
    height: theme.space['6'],
    lineHeight: theme.lineHeights.none,
    borderRadius: theme.radii.default,
    gap: theme.space['1'],
    paddingLeft: theme.space['2'],
    paddingRight: theme.space['2'],
    variants: {
        color: {
            primary: {
                color: theme.colors['primary-1'],
                backgroundColor: theme.colors['primary-5'],
            },
            success: {
                color: theme.colors['success-1'],
                backgroundColor: theme.colors['success-5'],
            },
            error: {
                color: theme.colors['error-1'],
                backgroundColor: theme.colors['error-5'],
            },
            warning: {
                color: theme.colors['warning-1'],
                backgroundColor: theme.colors['warning-5'],
            },
            grey: {
                color: theme.colors['grey-1'],
                backgroundColor: theme.colors['grey-5'],
            },
        },
    },
});

const StyledLabel = styled('span', {
    fontSize: theme.fontSizes.sm,
    fontWeight: theme.fontWeights.semibold,
});

// TODO: Need to figure out why @mdi/js isn't tree shaking
const mdiClose =
    'M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z';

export interface PillProps extends ComponentPropsWithRef<'div'> {
    /** Rendered color of the Pill */
    color?: 'primary' | 'success' | 'error' | 'warning' | 'grey';

    /** Toggle to show the close icon */
    closeable?: boolean;

    /** Callback triggered on close */
    onClose?: (event: React.MouseEvent) => void;

    /** Props to pass to the close */
    closeProps?: Omit<IconButtonProps, 'size'>;
}

const _Pill = (
    props: PillProps,
    ref: ForwardedRef<HTMLDivElement>,
): JSX.Element => {
    const {
        children,
        color = 'grey',
        closeable = true,
        onClose = () => null,
        closeProps = {},
        ...otherProps
    } = props;
    return (
        <StyledPill ref={ref} color={color} {...otherProps}>
            <StyledLabel>{children}</StyledLabel>
            {closeable && (
                <IconButton size="sm" onClick={onClose} {...closeProps}>
                    <Icon path={mdiClose} />
                </IconButton>
            )}
        </StyledPill>
    );
};

export const Pill = forwardRef(_Pill) as (
    props: PillProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _Pill>;
