import { memo, useContext, useMemo } from "react";
import { withJsonFormsControlProps, useJsonForms } from "@jsonforms/react";
import { ParentSize } from "@visx/responsive";
import { inputProps } from "../../interface/inputfieldProps";
import { DataContext } from "../../context/Context";
import { DrawHierarchyChart } from "./DrawhierarchyChart";

const HierarchyChart = memo(function (props: inputProps) {
  const { data, path, uischema, renderers, cells, enabled } = props;
  const uischemaData = uischema?.config?.main ?? {};
  const staticStyle = uischema?.config?.style ?? {};

  const ctx = useJsonForms();
  const { serviceProvider } = useContext(DataContext);

  const dynamicStyle = useMemo(() => {
    return serviceProvider(
      ctx,
      {
        onClick: uischemaData.styleFunction || "getStyle",
      },
      {
        event: { _reactName: "onClick" },
        path,
      }
    );
  }, [data, path, ctx, serviceProvider, uischemaData.styleFunction]);

  const componentStyle = useMemo(
    () => ({ ...staticStyle, ...dynamicStyle }),
    [staticStyle, dynamicStyle]
  );

  const linkType: string = uischemaData.linkType ?? "step";
  const stepPercent: number = Number(uischemaData.stepPercent) || 0.5;
  const nodeWidth: number = Number(uischemaData.nodeWidth) || 250;
  const nodeHeight: number = Number(uischemaData.nodeHeight) || 80;
  const chartHeight: number = Number(uischemaData.chartHeight) || 1000;
  const islazyLoad: boolean = uischemaData.lazyLoading === true;
  const lazyLoadFunction: string = uischemaData.lazyLoadFunction ?? "onNodeExpandChange";

  const nodeElements: any[] = uischema?.elements ?? [];
  if (!data) return null;

  return (
    <div
      style={{
        width: "100%",
        height: chartHeight,
        borderRadius: 14,
        overflow: "hidden",
        ...componentStyle.containerStyle,
      }}
    >
      <ParentSize>
        {({ width, height }) => (
          <DrawHierarchyChart
            path={path}
            width={width}
            height={height || chartHeight}
            data={data}
            linkType={linkType}
            stepPercent={stepPercent}
            nodeWidth={nodeWidth}
            nodeHeight={nodeHeight}
            styleConfig={componentStyle}
            renderers={renderers}
            cells={cells}
            enabled={enabled}
            nodeElements={nodeElements}
            islazyLoad={islazyLoad}
            lazyLoadFunction={lazyLoadFunction}
          />
        )}
      </ParentSize>
    </div>
  );
});

export default withJsonFormsControlProps(HierarchyChart);
