import type { ReactNode } from 'react';
import { TableBody as AriaTableBody } from 'react-aria-components';
import { Table } from './table';

export type DynamicColumn = {
    id: string;
    label: string;
    headerRenderer?: () => ReactNode;
    width?: string;
};

export type DynamicRow = {
    id: string;
    [key: string]: any;
};

interface DynamicTableProps<T extends DynamicRow> {
    columns: DynamicColumn[];
    rows: T[];
    renderCell: (row: T, columnId: string) => ReactNode;
    rowClassName?: (row: T) => string;
    size?: 'sm' | 'md';
    maxRows?: number;
    className?: string;
}

export const DynamicTable = <T extends DynamicRow>({
    columns,
    rows,
    renderCell,
    rowClassName,
    size = 'sm',
    maxRows,
    className,
}: DynamicTableProps<T>) => {
    const displayRows = maxRows ? rows.slice(0, maxRows) : rows;

    return (
        <Table size={size} aria-label="Dynamic table" className={className}>
            <Table.Header>
                {columns.map(col => (
                    <Table.Head key={col.id} id={col.id} label={col.headerRenderer ? '' : col.label}>
                        {col.headerRenderer?.()}
                    </Table.Head>
                ))}
            </Table.Header>
            <AriaTableBody items={displayRows}>
                {(row) => (
                    <Table.Row
                        id={row.id}
                        className={rowClassName?.(row)}
                    >
                        {columns.map(col => (
                            <Table.Cell key={col.id}>
                                {renderCell(row, col.id)}
                            </Table.Cell>
                        ))}
                    </Table.Row>
                )}
            </AriaTableBody>
        </Table>
    );
};
