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

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

const StyledHead = styled('thead', {
    variants: {
        sticky: {
            true: {
                position: 'sticky',
                top: '0',
            },
            false: {},
        },
    },
});

export type TableHeadProps = ComponentPropsWithRef<'thead'>;

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

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

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

export const TableHead = forwardRef(_TableHead) as (
    props: TableHeadProps & {
        ref?: ForwardedRef<HTMLTableSectionElement>;
    },
) => ReturnType<typeof _TableHead>;
