import {
  Box,
  Skeleton,
  Table as MuiTable,
  TableBody,
  TableCell,
  TableHead,
  TableRow as MuiTableRow,
  type TableProps as MuiTableProps,
} from '@mui/material'
import { styles } from './style'

export interface TableSkeletonProps {
  /** Number of body rows to render. Defaults to `5` (matches v1). */
  rows?: number
  /** Number of columns to render. Defaults to `4` (matches v1). */
  columns?: number
  /**
   * Forwarded to MUI's `<Table size>` so the loading layout matches the
   * size you'll render in {@link TableUI}. Leave `undefined` (the
   * default) to use MUI's own default density.
   */
  size?: MuiTableProps['size']
}

/**
 * Loading placeholder for the Table widget. Renders the same MUI table
 * primitives that {@link TableUI} uses so the loading layout (column
 * widths, header band, row density) doesn't shift when data resolves.
 *
 * Mirrors the v1 widget's `<TableSkeleton>` structure with v2's themed
 * `styles.headerCell`.
 */
export function TableSkeleton({
  rows = 5,
  columns = 4,
  size,
}: TableSkeletonProps) {
  return (
    <Box sx={styles.container} aria-label='Table skeleton'>
      <MuiTable size={size} sx={styles.table} stickyHeader>
        <TableHead>
          <MuiTableRow>
            {Array.from({ length: columns }).map((_, c) => (
              <TableCell key={`head-${c}`} sx={styles.headerCell}>
                <Skeleton variant='text' width='80%' height={24} />
              </TableCell>
            ))}
          </MuiTableRow>
        </TableHead>
        <TableBody>
          {Array.from({ length: rows }).map((_, r) => (
            <MuiTableRow key={`row-${r}`} sx={styles.row}>
              {Array.from({ length: columns }).map((__, c) => (
                <TableCell key={`cell-${r}-${c}`}>
                  <Skeleton variant='text' width='70%' height={20} />
                </TableCell>
              ))}
            </MuiTableRow>
          ))}
        </TableBody>
      </MuiTable>
    </Box>
  )
}
