/* eslint-disable react/no-array-index-key */
import React, { FunctionComponent } from 'react';
import cn from 'classnames';

import { TableHead, TableRow, TableHeader, TableCell, TableDivider } from './components';
import { StyledTableHeaderComponent } from './styled-components';
import { useTheme } from '../Theme';
import { TableCellProps, TableProps } from './types.d';
import { TableContext, useInitTableContext } from './context';

const SqTable: FunctionComponent<TableProps> = ({ data, children, style, className = '' }): React.ReactElement => {
  const numberOfColumns = data ? data[0].data.length : 0;
  const theme = useTheme();
  const classNames = cn({
    square_table__table: true,
    [className]: true,
  });

  const context = useInitTableContext();

  return (
    <TableContext.Provider value={context}>
      <div className={classNames} style={style}>
        {data ? (
          <>
            <StyledTableHeaderComponent className="square_table__row square_table__row_head" $theme={theme}>
              {data.map((h) => (
                <TableHead key={h.heading.toString()}>{h.heading}</TableHead>
              ))}
            </StyledTableHeaderComponent>
            {Array(numberOfColumns)
              .fill('')
              .map((a, index) => {
                const rowData = data.map((col) => ({ children: col.data[index], heading: col.heading } as TableCellProps));
                return <TableRow key={`${index} ${index}`} data={rowData} />;
              })}
          </>
        ) : null}
        {children}
      </div>
    </TableContext.Provider>
  );
};

export const Table = Object.assign(SqTable, {
  Header: TableHeader,
  Head: TableHead,
  // Body: TableBody as unknown as React.FC,
  Row: TableRow,
  Cell: TableCell,
  Divider: TableDivider,
});
