import {
  Table as MuiTable,
  TableBody,
  TableCell,
  TableHead,
  TableContainer as MuiTableContainer,
  Paper,
  type TableProps as MuiTableProps,
} from '@mui/material'
import type { Ref } from 'react'
import { CellHeader } from './components/cell-header'
import { Row } from './components/row'
import { Pagination } from './components/pagination'
import { PaginationActions } from './components/pagination-actions'
import { useWidgetRef } from '../../hooks'
import type { TableUIProps } from './types'

/**
 * Props for the base Table component
 */
interface TableComponentProps extends MuiTableProps {
  /** Table element ref */
  ref?: Ref<HTMLTableElement>
}

/**
 * Base Table component with compound component pattern
 * Provides Table.Head, Table.Body, Table.Row, Table.Cell, Table.CellHeader, Table.Pagination
 */
function Table({
  children,
  ref,
  stickyHeader = true,
  ...props
}: TableComponentProps) {
  return (
    <MuiTable stickyHeader={stickyHeader} ref={ref} {...props}>
      {children}
    </MuiTable>
  )
}

// Attach sub-components as static properties
Table.Head = TableHead
Table.CellHeader = CellHeader
Table.Body = TableBody
Table.Row = Row
Table.Cell = TableCell
Table.Container = TableContainer
Table.Paper = Paper
Table.Pagination = Pagination
Table.PaginationActions = PaginationActions

export { Table }

/**
 * TableContainer widget component
 * Integrates with widget store and provides ref registration using custom hook
 */
function TableContainer(props: TableUIProps) {
  const { ref } = useWidgetRef<HTMLDivElement>(props.id)

  return <MuiTableContainer ref={ref}>{props.children}</MuiTableContainer>
}
