import { ParentSize } from "@visx/responsive";
import TreeMap from "./TreeMap";
import { withJsonFormsControlProps } from "@jsonforms/react";
import { inputProps } from "../../interface/inputfieldProps";
import _ from "lodash";
import { useEffect, useState } from "react";
import { Divider } from "@mui/material";
import {
  ActionButton,
  adjustZoom,
  assignUniqueIds,
  getInitialDimensions,
  validate,
} from "./TreeHelperComponents";
import { DimensionType } from "./interface";

function TreeMapWrapper(props: inputProps) {
  const { uischema, path, data } = props;
  const uischemaConfig = uischema?.config;
  const uiSchemaData = uischema?.config?.main;
  const dimensionInitial: DimensionType = getInitialDimensions(uiSchemaData);
  const [dimension, setDimension] = useState(dimensionInitial);
  const [zoom, setZoom] = useState(false);
  const [treeData, setTreeData] = useState(assignUniqueIds(validate(data)));
  useEffect(() => {
    if (!_.isEqual(data, treeData)) {
      setTreeData(assignUniqueIds(data));
    }
  }, [data,data?.length]);
  return (
    <div
      style={{
        height: dimension.containerHeight,
        borderRadius: "5px",
        width: "100%",
        position: "relative",
        overflowX: "auto",
        overflowY: "auto",
        scrollbarWidth: "none",
        msOverflowStyle: "none",
        ...dimension?.container?.style,
        ...uischemaConfig?.style?.containerStyle,
      }}
    >
      <div
        style={{
          height: zoom ? dimension.graphZoomHeight : dimension.graphHeight,
          width: zoom ? dimension.graphZoomWidth : dimension.graphWidth,
          position: "relative",
          borderRadius: "5px",
          background: "white",
          scrollbarWidth: "none",
          msOverflowStyle: "none",
          overflow: "scroll",
        }}
      >
        <div
          style={{
            textAlign: "left",
            padding: "5px",
            paddingLeft: "10px",
            paddingBottom: "5px",
            fontWeight: "bolder",
            borderRadius: "5px",
            background: uiSchemaData?.background || "#ffffff",
            ...uiSchemaData?.config?.style?.headerStyle,
          }}
        >
          {uiSchemaData.header}
        </div>
        <Divider></Divider>

        <ActionButton
          dimension={dimension}
          adjustZoom={adjustZoom}
          setDimension={setDimension}
          zoom={zoom}
          setZoom={setZoom}
          dimensionInitial={dimensionInitial}
        />
        <ParentSize>
          {({ width, height }) => (
            <TreeMap
              dimension={dimension}
              treeData={treeData}
              setTreeData={setTreeData}
              {...props}
              width={width}
              height={height}
            />
          )}
        </ParentSize>
      </div>
    </div>
  );
}

export default withJsonFormsControlProps(TreeMapWrapper);
