import React, { useContext } from 'react'
import type { ContentTreeWorkarounds } from '@financial-times/cp-content-pipeline-schema'
import { ColumnSettingsContext } from '.'
import classNames from 'classnames'
import { ContentProps } from '../../types'

interface TableCellProps
  extends ContentProps<ContentTreeWorkarounds.TableCell> {}

export const TableCell: React.FC<React.PropsWithChildren<TableCellProps>> = (
  props
) => {
  const allColumnSettings = useContext(ColumnSettingsContext)
  const columnSettings: ContentTreeWorkarounds.TableColumnSettings =
    (typeof props.parentIndex === 'number'
      ? allColumnSettings[props.parentIndex]
      : undefined) ?? {
      hideOnMobile: false,
      sortable: false,
    }

  return props.content.heading ? (
    <th
      className={classNames({
        'n-content-body__table-cell--hide-mobile': columnSettings.hideOnMobile,
      })}
      data-o-table-data-type={columnSettings.sortType}
      data-o-table-heading-disable-sort={!columnSettings.sortable || undefined}
      scope="col"
      role="columnheader"
    >
      {props.children}
    </th>
  ) : (
    <td
      className={classNames({
        'o-table__cell--numeric': columnSettings.sortType === 'number',
        'n-content-body__table-cell--hide-mobile': columnSettings.hideOnMobile,
      })}
    >
      {props.children}
    </td>
  )
}
