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

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

const StyledBody = styled('tbody', {});

// extend the native props
export type TableBodyProps = ComponentPropsWithRef<'tbody'>;

const _TableBody = (
    props: TableBodyProps,
    ref: ForwardedRef<HTMLTableSectionElement>,
): JSX.Element => {
    const { children, ...otherProps } = props;

    // get the table and set the cell as body
    const table = useTable({
        cellType: 'body',
    });

    return (
        <TableContext.Provider value={table}>
            <StyledBody ref={ref} {...otherProps}>
                {children}
            </StyledBody>
        </TableContext.Provider>
    );
};

export const TableBody = forwardRef(_TableBody) as (
    props: TableBodyProps & {
        ref?: ForwardedRef<HTMLTableSectionElement>;
    },
) => ReturnType<typeof _TableBody>;
