import React, { FunctionComponent, Children, useContext } from 'react';
import cn from 'classnames';

import { StyledTableRow } from '../styled-components';
import { useTheme } from '../../Theme';
import { TableCell } from './cell';
import { TableRowProps } from '../types.d';
import { TableContext } from '../context';

export const TableRow: FunctionComponent<TableRowProps> = ({ data, children, style, className = '', bold = false }) => {
  const theme = useTheme();

  const classNames = cn({
    [className]: true,
    square_table__row: true,
    bold,
  });

  const { columnSettings } = useContext(TableContext);

  const numberOfChildren = Children.count(children);

  const getChildrenWithProps = () => {
    if (columnSettings.length === 0) return children;
    return Children.map(children, (child, index) => {
      const isLastChild = numberOfChildren - 1 === index;
      // checking isValidElement is the safe way and avoids a typescript error too
      if (React.isValidElement(child)) {
        const currentColumn = columnSettings[index];
        return React.cloneElement(child, { isNote: isLastChild ? false : currentColumn.isNote, heading: currentColumn.header });
      }
      return child;
    });
  };

  return (
    <StyledTableRow $theme={theme} $bold={bold} className={classNames} style={style}>
      {data
        ? data.map((c, index) => {
            // const isLastOrFirstRow = index === data.length - 1 || index === 0;
            const key = `${index} + ${c.heading?.toString() ?? ''}`;
            return (
              // eslint-disable-next-line react/no-array-index-key
              <TableCell key={key} heading={c.heading}>
                {c.children}
              </TableCell>
            );
          })
        : null}
      {getChildrenWithProps()}
    </StyledTableRow>
  );
};
