import { FC, MouseEvent, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { PanelBar } from "@/components/PanelBar";
import { getPageDisplayNameMapViewDisplayName } from "@/redux/currentApp/components/componentsSelector";
import { RootComponentNodeProps } from "@/redux/currentApp/components/componentsState";
import { getRootNodeExecutionResult } from "@/redux/currentApp/executionTree/executionSelector";
import { FocusManager } from "@/utils/focusManager";
import PageItem from "./components/PageItem";
import { pageSpaceTreeStyle } from "./style";
import IconHotSpot from "@/utils/IconHotSpot";
import PlusIcon from "@mui/icons-material/Add";
import { componentsActions } from "@/redux/currentApp/components/componentsSlice";
import { generatePageConfig } from "@/utils/generators/generatePageOrSectionConfig";
export const PageSpaceTree: FC = () => {
  const { t } = useTranslation();
  const rootNodeProps = useSelector(
    getRootNodeExecutionResult
  ) as RootComponentNodeProps;
  const {
    currentPageIndex,
    homepageDisplayName,
    pageSortedKey = [],
    currentSubPagePath,
  } = rootNodeProps;

  const currentPageDisplayName = pageSortedKey[currentPageIndex];
  const dispatch = useDispatch();

  const handleClickAddButton = useCallback(
    (e: MouseEvent<HTMLButtonElement>) => {
      e.stopPropagation();
      const newPageConfig = generatePageConfig();
      // this will delete because page will add from impaktApps

      dispatch(
        componentsActions.addPageNodeWithSortOrderReducer(newPageConfig)
      );
    },
    [dispatch]
  );
  const pageDisplayNameMapSubPageDisplayName = useSelector(
    getPageDisplayNameMapViewDisplayName
  );

  return (
    <PanelBar
      title={t("editor.data_work_space.pages_title")}
      destroyChildrenWhenClose
      customIcon={
        <IconHotSpot onClick={handleClickAddButton}>
          <PlusIcon sx={{ fontSize: "14px" }} />
        </IconHotSpot>
      }
      onIMPAKTAPPSFocus={() => {
        FocusManager.switchFocus("data_page");
      }}
    >
      <div css={pageSpaceTreeStyle}>
        {Object.keys(pageDisplayNameMapSubPageDisplayName).map((key, index) => {
          const isHomePage = homepageDisplayName
            ? homepageDisplayName === key
            : index === 0;
          return (
            <PageItem
              isHomePage={isHomePage}
              pageName={key}
              key={key}
              level={1}
              subPagePaths={pageDisplayNameMapSubPageDisplayName[key]}
              currentPagePath={currentPageDisplayName}
              currentSubPagePath={currentSubPagePath}
            />
          );
        })}
      </div>
    </PanelBar>
  );
};
