import { TableCell, TableSortLabel, Checkbox } from '@mui/material'
import type { CellHeaderProps } from '../types'

/**
 * Table cell header component with optional sorting and select-all checkbox
 */
export function CellHeader({
  column,
  sortState,
  onSort,
  isSelectAll,
  isAllSelected,
  isIndeterminate,
  onSelectAll,
}: CellHeaderProps) {
  // Render select-all checkbox
  if (isSelectAll) {
    return (
      <TableCell padding='checkbox'>
        <Checkbox
          checked={isAllSelected}
          indeterminate={isIndeterminate}
          onChange={onSelectAll}
          inputProps={{ 'aria-label': 'select all rows' }}
        />
      </TableCell>
    )
  }

  const isSorted = sortState?.columnId === column.id
  const sortDirection = isSorted ? sortState.direction : undefined

  // Render sortable column header
  if (column.sortable && onSort) {
    return (
      <TableCell
        align={column.align}
        style={{ width: column.width }}
        sortDirection={sortDirection}
      >
        <TableSortLabel
          active={isSorted}
          direction={sortDirection ?? 'asc'}
          onClick={() => onSort(column.id)}
        >
          {column.label}
        </TableSortLabel>
      </TableCell>
    )
  }

  // Render non-sortable column header
  return (
    <TableCell align={column.align} style={{ width: column.width }}>
      {column.label}
    </TableCell>
  )
}
