import React from "react";
import isEmpty from "lodash/isEmpty";
import type { UISchemaElement } from "@jsonforms/core";
import {
  JsonFormsCellRendererRegistryEntry,
  JsonFormsRendererRegistryEntry,
  JsonSchema,
  OwnPropsOfRenderer,
} from "@jsonforms/core";
import { JsonFormsDispatch, useJsonForms } from "@jsonforms/react";
import Grid from "@mui/material/Grid2";
import { isHidden } from "../common/getHiddenKeys";

export const renderLayoutElements = (
  elements: any,
  schema: JsonSchema | undefined,
  path: string | undefined,
  enabled: boolean | undefined,
  renderers?: JsonFormsRendererRegistryEntry[],
  cells?: JsonFormsCellRendererRegistryEntry[]
) => {
  return elements.map((child: any, index: number) => {
    if (isHidden(child, schema)) {
      return null;
    }
    return (
      <Grid
        key={`${path}-${index}`}
        size={{
          xs: child?.config?.layout
            ? child?.config?.layout.xs
              ? child?.config?.layout.xs
              : child?.config?.layout
            : 12,
          sm: child?.config?.layout
            ? child?.config?.layout.sm
              ? child?.config?.layout.sm
              : child?.config?.layout
            : 12,
          md: child?.config?.layout
            ? child?.config?.layout.md
              ? child?.config?.layout.md
              : child?.config?.layout
            : 12,
          lg: child?.config?.layout
            ? child?.config?.layout.lg
              ? child?.config?.layout.lg
              : child?.config?.layout
            : 12,
        }}
        sx={{
          display: {
            xs: child?.config?.layout?.xs === 0 ? "none" : "block",
            sm: child?.config?.layout?.sm === 0 ? "none" : "block",
            md: child?.config?.layout?.md === 0 ? "none" : "block",
            lg: child?.config?.layout?.lg === 0 ? "none" : "block",
          },
        }}
      >
        <JsonFormsDispatch
          uischema={child}
          schema={schema}
          path={path}
          enabled={enabled}
          renderers={renderers}
          cells={cells}
        />
      </Grid>
    );
  });
};

export interface MaterialLayoutRendererProps extends OwnPropsOfRenderer {
  elements: UISchemaElement[];
  direction: "row" | "column";
}
const MaterialLayoutRendererComponent = ({
  visible,
  elements,
  schema,
  path,
  enabled,
  direction,
  renderers,
  cells,
}: MaterialLayoutRendererProps) => {
  if (isEmpty(elements)) {
    return null;
  } else {
    return (
      <Grid
        container
        direction={direction}
        spacing={direction === "row" ? 2 : 0}
        sx={{
          justifyContent: "space-around",
        }}
      >
        {renderLayoutElements(
          elements,
          schema,
          path,
          enabled,
          renderers,
          cells
        )}
      </Grid>
    );
  }
};
export const MaterialLayoutRenderer = React.memo(
  MaterialLayoutRendererComponent
);
