import { ComponentPropsWithRef, forwardRef, ForwardedRef } from 'react';
import { Item } from '@radix-ui/react-dropdown-menu';

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

const StyledDropdownItem = styled(Item, {
    display: 'flex',
    alignItems: 'center',
    flex: '1 1 0',
    minHeight: theme.space['8'],
    padding: `0 ${theme.space['4']}`,
    color: theme.colors['grey-1'],
    backgroundColor: theme.colors['base'],
    cursor: 'pointer',
    outline: 'none',
    overflow: 'hidden',
    fontSize: theme.fontSizes.sm,
    borderRadius: theme.radii.default,
    '&[data-disabled]': {
        color: theme.colors['grey-3'],
        pointerEvents: 'none',
    },
    '&[data-highlighted]': {
        background: theme.colors['primary-5'],
    },
});

export interface DropdownItemProps
    extends Omit<ComponentPropsWithRef<'div'>, 'onSelect'> {
    /** Mark the item in a disabled/enabled state */
    disabled?: boolean;

    /** Callback that is triggered when the item is selected */
    onSelect?: (event: Event) => void;
}

/**
 * DropdownItem component
 */
const _DropdownItem = (
    props: DropdownItemProps,
    ref: ForwardedRef<HTMLDivElement>,
): JSX.Element => {
    const {
        children,
        onSelect = () => null,
        disabled = false,
        ...otherProps
    } = props;

    return (
        <StyledDropdownItem
            ref={ref}
            disabled={disabled}
            onSelect={onSelect}
            {...otherProps}
        >
            {children}
        </StyledDropdownItem>
    );
};

export const DropdownItem = forwardRef(_DropdownItem) as (
    props: DropdownItemProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _DropdownItem>;
