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

import { useTable } from './TableContext';

const StyledTableCell = styled('td', {
    fontSize: theme.fontSizes.sm,
    paddingTop: theme.space['2'],
    paddingRight: theme.space['4'],
    paddingBottom: theme.space['2'],
    paddingLeft: theme.space['4'],
    variants: {
        header: {
            true: {
                textAlign: 'left',
                paddingTop: '0',
                paddingBottom: '0',
                whiteSpace: 'nowrap',
                verticalAlign: 'middle',
                '&::before': {
                    content: '',
                    borderLeftColor: theme.colors['grey-4'],
                    borderLeftWidth: theme.borderWidths.default,
                    marginLeft: theme.space['-4'],
                    paddingLeft: theme.space['4'],
                },
                '&:first-child': {
                    '&::before': {
                        content: 'none',
                    },
                },
            },
            false: {
                verticalAlign: 'top',
            },
        },
    },
});

export interface BaseTableCell {
    /** Vertical Alignment of the cell */
    verticalAlign?: StitchesCSS['verticalAlign'];

    /** Width of the cell */
    width?: StitchesCSS['width'];
}

export type TableCellProps2 = (
    | ComponentPropsWithRef<'td'>
    | ComponentPropsWithRef<'th'>
) &
    BaseTableCell;

export type HeaderTableCell = BaseTableCell & ComponentPropsWithRef<'th'>;

export type DataTableCell = BaseTableCell & ComponentPropsWithRef<'td'>;

export type TableCellProps<H extends boolean> = H extends true
    ? HeaderTableCell
    : DataTableCell;

const _TableCell = <H extends boolean>(
    props: TableCellProps<H>,
    ref: ForwardedRef<HTMLTableCellElement>,
): JSX.Element => {
    const { children, verticalAlign = '', width = '', ...otherProps } = props;

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

    return (
        <StyledTableCell
            ref={ref}
            as={table.cellType === 'head' ? 'th' : 'td'}
            header={table.cellType === 'head'}
            css={{
                verticalAlign: verticalAlign,
                width: width,
            }}
            {...otherProps}
        >
            {children}
        </StyledTableCell>
    );
};

export const TableCell = forwardRef(_TableCell) as <H extends boolean>(
    props: TableCellProps<H> & {
        ref?: ForwardedRef<HTMLTableCellElement>;
    },
) => ReturnType<typeof _TableCell>;
