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

export const ColumnSettingsContext = createContext<
  ContentTreeWorkarounds.TableColumnSettings[]
>([])

interface TableProps extends ContentProps<ContentTreeWorkarounds.Table> {}

const Table: React.FC<React.PropsWithChildren<TableProps>> = ({
  children,
  content: {
    compact,
    layoutWidth,
    stripes,
    responsiveStyle,
    columnSettings,
    collapseAfterHowManyRows,
  },
}) => {
  return (
    <ColumnSettingsContext.Provider value={columnSettings}>
      <div
        className={classNames('o-table-container n-content-layout', {
          'o-table-container--contracted': Boolean(collapseAfterHowManyRows),
        })}
        data-layout-width={layoutWidth}
        data-component="table"
      >
        <div
          className={classNames('o-table-overlay-wrapper', {
            'n-content-layout__container': layoutWidth !== 'auto',
          })}
        >
          <div className="o-table-scroll-wrapper">
            <table
              className={classNames(
                'o-table',
                `o-table--responsive-${responsiveStyle}`,
                {
                  'o-table--compact': compact,
                  'o-table--row-stripes': stripes,
                  'o-table--horizontal-lines': !stripes,
                }
              )}
              data-o-component="o-table"
              data-o-table-responsive={responsiveStyle}
              data-o-table-minimum-row-count={collapseAfterHowManyRows}
              data-o-table-expanded={String(!collapseAfterHowManyRows)}
            >
              {children}
            </table>
          </div>
        </div>
      </div>
    </ColumnSettingsContext.Provider>
  )
}

export default Table
