/* eslint-disable react/no-array-index-key */
import elementsRender from '../config/elements-render';
import type { Elements as ActionElements } from '../config/map/actions';
import type { Elements as ValuesElements } from '../config/map/values';
import { Divider } from 'ui/elements';
import type { GridProps } from 'ui/grid';
import { Grid } from 'ui/grid';

export type ElementsRow = [elements: Array<ActionElements | ValuesElements>, style?: GridProps];
type DividerRow = { title: string };

export type FormTabRows = Array<DividerRow | ElementsRow>;

function renderFormRows(rowsConfig: FormTabRows) {
  const rows = rowsConfig.map((row, i) => {
    if (Array.isArray(row)) {
      const [elements, style] = row;
      const renderedElements = elements.map((elementName) => {
        const Render = elementsRender[elementName]?.render;

        return <Render key={elementName} />;
      });

      return (
        <Grid
          key={i.toString()}
          gap="10px"
          gridTemplateColumns={['1fr', '1fr', 'repeat(3, 1fr)']}
          {...style}
        >
          {renderedElements}
        </Grid>
      );
    }

    const { title } = row;

    return <Divider key={i.toString()}>{title}</Divider>;
  });

  return <Grid gridAutoRows="auto">{rows}</Grid>;
}

export default renderFormRows;
