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

export type ElementsRow = [elements: (ValuesElements | ActionElements)[], style?: BoxProps['sx']];
type DividerRow = { title: string };

export type FormTabRows = Array<ElementsRow | DividerRow>;

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;

        // eslint-disable-next-line object-curly-newline
        return render({});
      });

      return (
        <Box
          key={i.toString()}
          sx={{
            display: 'grid',
            gridTemplateColumns: ['1fr', '1fr', 'repeat(3, 1fr)'],
            gap: '10px',
            ...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;
