import Divider from 'Elements/layout/Divider';
import type { BoxProps } from 'UIKit/grid';
import { Box } from 'UIKit/grid';
import elementsRender from '../config/elements-render';
import type { Elements as ActionElements } from '../config/map/actions';
import type { Elements as ComputedElements } from '../config/map/computed';
import type { Elements as ValuesElements } from '../config/map/values';

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

export type FormComponentConfig = {
  id: string;
  title: string;
  rows: Array<ElementsRow | DividerRow>;
};

function renderFormComponent(config: FormComponentConfig) {
  const rows = config.rows.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
          // eslint-disable-next-line react/no-array-index-key
          key={i.toString()}
          sx={{
            display: 'grid',
            gridTemplateColumns: ['1fr', '1fr', 'repeat(3, 1fr)'],
            gap: '10px',
            ...style,
          }}
        >
          {renderedElements}
        </Box>
      );
    }

    const { title } = row;

    return <Divider>{title}</Divider>;
  });

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

export default renderFormComponent;
