/* 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/layout/Divider';
import type { BoxProps } from 'ui/grid';
import { Box } from 'ui/grid';

export type ElementsRow = [
  elements: Array<ActionElements | ValuesElements>,
  style?: BoxProps['sx']
];
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({});
      });

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

    const { title } = row;

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

  return (
    <Box
      sx={{
        display: 'grid',
        gridAutoRows: 'auto',
      }}
    >
      {rows}
    </Box>
  );
}

export default renderFormRows;
