import { ComponentPropsWithRef, forwardRef, ForwardedRef } from 'react';
import { Trigger } from '@radix-ui/react-tabs';

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

const StyledTabsTrigger = styled(Trigger, {
    flexShrink: '0',
    position: 'relative',
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    textAlign: 'center',
    fontSize: theme.fontSizes.sm,
    fontWeight: theme.fontWeights.semibold,
    lineHeight: theme.lineHeights.none,
    height: `${theme.space[8]}`,
    padding: `${theme.space[1]} ${theme.space[4]}`,
    outline: 'none',
    borderBottomWidth: theme.borderWidths.thick,
    borderBottomColor: theme.colors['grey-4'],
    marginBottom: `calc(-1 * ${theme.borderWidths.thick})`,
    '&:hover': {
        backgroundColor: theme.colors['primary-5'],
    },
    '&:focus': {
        outline: `2px solid ${theme.colors['primary-1']}`,
        outlineOffset: '2px',
        zIndex: 1,
    },
    '&[data-state="active"]': {
        borderBottomColor: theme.colors['primary-1'],
    },
    '&[data-disabled]': {
        color: theme.colors['grey-3'],
        cursor: 'default',
        pointerEvents: 'none',
        '&[data-state="active"]': {
            borderBottomColor: theme.colors['grey-2'],
        },
    },
});

export interface TabsTriggerProps extends ComponentPropsWithRef<'button'> {
    /** Value of the trigger */
    value: string;

    /** Mark the input in a disabled/enabled state */
    disabled: boolean;
}

const _TabsTrigger = (
    props: TabsTriggerProps,
    ref: ForwardedRef<HTMLButtonElement>,
): JSX.Element => {
    const { children, value, disabled = false, ...otherProps } = props;
    return (
        <StyledTabsTrigger
            ref={ref}
            value={value}
            disabled={disabled}
            type={'button'}
            {...otherProps}
        >
            {children}
        </StyledTabsTrigger>
    );
};

export const TabsTrigger = forwardRef(_TabsTrigger) as (
    props: TabsTriggerProps & {
        ref?: ForwardedRef<HTMLButtonElement>;
    },
) => ReturnType<typeof _TabsTrigger>;
