import React, { forwardRef, HTMLAttributes, PropsWithChildren } from 'react';
import { observer } from 'mobx-react-lite';
import { LoadingRowState } from '../LoadingRow/LoadingRowState';
import { LoadingRowTD } from '../LoadingRow/LoadingRowTD';

interface TableBaseRowProps extends HTMLAttributes<HTMLTableRowElement> {
  state: LoadingRowState;
  rowData: { id: string };
}

export const TableBaseRow = observer(
  forwardRef((props: PropsWithChildren<TableBaseRowProps>, ref: any) => {
    const { state, rowData, children, ...rest } = props;
    const isLoadingRow = state.isLoading(rowData.id);
    return (
      <tr
        ref={ref}
        {...rest}
        style={{
          ...rest.style,
          position: isLoadingRow ? 'relative' : rest.style?.position,
        }}
      >
        {isLoadingRow && Array.isArray(children)
          ? children.map((child, index) => {
              return index === children.length - 1 ? (
                <LoadingRowTD key={index} state={state} replacedCell={child} />
              ) : (
                React.cloneElement(child, {
                  key: index,
                  style: { visibility: 'hidden' },
                })
              );
            })
          : children}
      </tr>
    );
  }),
);
