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

import { useTable } from './TableContext';

const StyledTableRow = styled('tr', {
    variants: {
        header: {
            true: {
                backgroundColor: theme.colors['grey-5'],
                height: theme.space['10'],
                fontWeight: theme.fontWeights.semibold,
                paddingTop: theme.space['2'],
                paddingBottom: theme.space['2'],
                '&:last-child': {
                    borderBottomWidth: theme.borderWidths.default,
                    borderBottomColor: theme.colors['grey-4'],
                },
            },
            false: {},
        },
        highlight: {
            true: {},
            false: {},
        },
        striped: {
            true: {},
            false: {},
        },
    },
    compoundVariants: [
        {
            css: {
                '&:nth-child(even)': {
                    backgroundColor: theme.colors['grey-5'],
                },
            },
            header: false,
            striped: true,
        },
        {
            css: {
                borderTopWidth: theme.borderWidths.default,
                borderTopColor: theme.colors['grey-4'],
                '&:first-child': {
                    borderTopColor: 'transparent',
                },
            },
            header: false,
            striped: false,
        },
        {
            css: {
                '&:hover': {
                    backgroundColor: theme.colors['primary-5'],
                },
            },
            header: false,
            highlight: true,
        },
    ],
});

export type TableRowProps = ComponentPropsWithRef<'tr'>;

const _TableRow = (
    props: TableRowProps,
    ref: ForwardedRef<HTMLTableRowElement>,
): JSX.Element => {
    const { children, ...otherProps } = props;

    // get the table
    const table = useTable();

    return (
        <StyledTableRow
            ref={ref}
            highlight={table.highlight}
            striped={table.striped}
            header={table.cellType === 'head'}
            {...otherProps}
        >
            {children}
        </StyledTableRow>
    );
};

export const TableRow = forwardRef(_TableRow) as (
    props: TableRowProps & {
        ref?: ForwardedRef<HTMLTableRowElement>;
    },
) => ReturnType<typeof _TableRow>;
