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

import { TableContext, TableValue } from './TableContext';

export interface TableProps extends ComponentPropsWithRef<'table'> {
    /** Show the border **/
    border?: boolean;

    /** Layout the table */
    layout?: StitchesCSS['tableLayout'];

    /** Make the head fixed as a user scrolls */
    sticky?: TableValue['sticky'];

    /** Highlight rows on hover */
    highlight?: TableValue['highlight'];

    /** Add strips to the rows */
    striped?: TableValue['striped'];
}

const StyledTable = styled('table', {
    position: 'relative',
    display: 'table',
    backgroundColor: theme.colors.base,
    color: theme.colors['grey-1'],
    width: theme.space['full'],
    overflowX: theme.space['auto'],
    variants: {
        border: {
            true: {
                borderColor: theme.colors['grey-4'],
                borderWidth: theme.borderWidths.default,
                borderRadius: theme.radii.default,
            },
        },
    },
});

const _Table = (
    props: TableProps,
    ref: ForwardedRef<HTMLTableElement>,
): JSX.Element => {
    const {
        border = true,
        layout = '',
        sticky = false,
        highlight = false,
        striped = true,
        children,
        ...otherProps
    } = props;

    // construct the value
    const value = {
        sticky: sticky,
        highlight: highlight,
        striped: striped,
        cellType: null,
    };

    return (
        <TableContext.Provider value={value}>
            <StyledTable
                ref={ref}
                border={border}
                css={{
                    tableLayout: layout,
                }}
                {...otherProps}
            >
                {children}
            </StyledTable>
        </TableContext.Provider>
    );
};

export const Table = forwardRef(_Table) as (
    props: TableProps & {
        ref?: ForwardedRef<HTMLTableElement>;
    },
) => ReturnType<typeof _Table>;
