import { FC, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector, useStore } from "react-redux";
import { PanelBar } from "@/components/PanelBar";
// import { WorkSpaceTreeGroup } from "@/page/app/Module/DataWorkspace/components/WormkSpaceTreeGroup"
import { getSelectedComponentDisplayNames } from "@/redux/config/configSelector"
import {
  getCurrentPageBodyWidgetTree,
} from "@/redux/currentApp/executionTree/executionSelector"
import { executionActions } from "@/redux/currentApp/executionTree/executionSlice"
import { ClickPosition, FocusManager } from "@/utils/focusManager"
import { BaseDataItem } from "../BaseDataItem"
import { WorkSpaceTreeGroup } from "../WorkSpaceTreeGroup"
import { configActions } from "@/redux/config/configSlice"

export const ComponentSpaceTree: FC = () => {
  const { t } = useTranslation()
  const dispatch = useDispatch()
  const bodySectionTree = useSelector(getCurrentPageBodyWidgetTree)
  const selectedComponent = useSelector(getSelectedComponentDisplayNames)

  const handleClick = useCallback(
    (displayName: string, type: string) => {
      const clickPosition: ClickPosition = {
        displayName,
        type: "component",
        clickPosition: [],
      }
      if (type === "CANVAS" || type === "NATIVECANVAS") {
        // displayName = autoChangeWhenClickOnCanvas(displayName)
        clickPosition.type = "inner_container"
        clickPosition.clickPosition = [0, 0]
      }
      FocusManager.switchFocus("data_component", clickPosition)
      if (type === "MODAL_WIDGET") {
        dispatch(
          executionActions.updateModalDisplayReducer({
            displayName,
            display: true,
          })
        );
      }
      if (displayName) {
        dispatch(configActions.updateSelectedComponent([displayName]))
    
        setTimeout(() => {
          const dom = document.querySelector(
            `[data-displayname="${displayName}"]`
          );
          dom?.scrollIntoView({ behavior: "smooth", block: "center" });
        }, 160);
      }
    },
    [dispatch]
  );

  return (
    <PanelBar
      title={t("editor.data_work_space.components_title")}
      destroyChildrenWhenClose
    >
      <WorkSpaceTreeGroup title={t("editor.page.label_name.body")}>
        {[...bodySectionTree].reverse().map((tree) => (
          <BaseDataItem
            key={tree.displayName}
            title={tree.displayName}
            value={tree}
            level={0}
            dataType="widget"
            type={tree.$widgetType as string}
            canExpand={tree.$childrenNode.length > 0}
            haveMoreAction
            onClick={handleClick}
            selectedDisplayNames={selectedComponent}
          />
        ))}
      </WorkSpaceTreeGroup>
    </PanelBar>
  );
};

ComponentSpaceTree.displayName = "ComponentSpaceTree";
