/* eslint-disable @typescript-eslint/no-explicit-any */
// import { ILLA_MIXPANEL_EVENT_TYPE } from "@illa-public/mixpanel-utils"
// import { getCurrentUserId } from "@illa-public/user-data"
import { klona } from "klona";
import { get } from "lodash-es";
import { FC, MouseEvent, useCallback, useContext, useMemo } from "react";
// import { useTranslation } from "react-i18next"
import { useDispatch, useSelector } from "react-redux";
// import { DropList, DropListItem, Dropdown } from "@illa-design/react"
import { BASIC_CANVAS_PADDING, UNIT_HEIGHT } from "@/page/app/components/DotPanel/constant/canvas";
import { AutoHeightWithLimitedContainer } from "@/page/app/components/ScaleSquare/components/AutoHeightWithLimitedContainer";
import { DEFAULT_MIN_COLUMN } from "@/page/app/components/ScaleSquare/constant/widget";
import {
  getCanvasShape,
  getHoveredComponents,
  getIsGridCanvas,
  getIsILLAEditMode,
  getIsLikeProductMode,
  getSelectedComponentDisplayNames,
  isShowDot,
} from "@/redux/config/configSelector";
import { configActions } from "@/redux/config/configSlice";
// import {
//   getComponentAttachUsers,
//   getTargetCurrentUsersExpendMe,
// } from "@/redux/currentApp/collaborators/collaboratorsSelector"
import { getComponentDisplayNameMapDepth, getComponentMap, searchComponentFromMap } from "@/redux/currentApp/components/componentsSelector";
// import { getFirstDragShadowInfo } from "@/redux/currentApp/dragShadow/dragShadowSelector"
import {
  getCurrentPageBodySection,
  // getExecutionError,
  getExecutionResult,
  getIsDragging,
  getResizingComponentIDs,
  getRootNodeExecutionResult,
} from "@/redux/currentApp/executionTree/executionSelector";
import { getClientWidgetLayoutInfo } from "@/redux/currentApp/layoutInfo/layoutInfoSelector";
import store, { RootState } from "@/store";
// import { CopyManager } from "@/utils/copyManager"
import { FocusManager } from "@/utils/focusManager";
// import { trackInEditor } from "@/utils/mixpanelHelper"
import { ShortCutContext } from "@/utils/shortcut/shortcutProvider"
// import { isMAC } from "@/utils/userAgent"
import { RESIZE_DIRECTION } from "@/widgetLibrary/interface";
// import { widgetBuilder } from "@/widgetLibrary/widgetBuilder"
// import { useMouseHover } from "../../utils/useMouseHover"
import { DragContainer } from "../DragContainer/index";
// import { MoveBar } from "../MoveBar/moveBar"
import { PositionContainer } from "../PositionContainer";
import ResizeHandler from "./ResizeHandler";
import { ResizingAndDragContainerProps } from "./interface";
import {
  resizingContainerStyle,
  resizingGridContainerStyle,
  resizingPlaceholderStyle,
} from "./style";
import { widgetBuilder } from "@/widgetLibrary/widgetBuilder";
import { MoveBar } from "../MoveBar/moveBar";
import { ComponentMapNode } from "@/utils/generators/interface";
import { DropList, DropListItem, Dropdown } from "@/utils/DropDown";
import { CopyManager } from "@/utils/copyManager";
import { t } from "i18next";
import { ILLA_MIXPANEL_EVENT_TYPE, trackInEditor } from "@/utils/mixpanelHelper";
// import { useMouseHover } from "../../utils/useMouseHover";
// import { getFirstDragShadowInfo } from "@/redux/currentApp/dragShadow/dragShadowSelector"

export const ResizingAndDragContainer: FC<ResizingAndDragContainerProps> = (
  props
) => {
  const {
    unitW,
    displayName,
    children,
    widgetHeight,
    widgetTop,
    widgetLeft,
    widgetWidth,
    widgetType,
    
    columnNumber,
    parentNodeDisplayName,
  } = props;

  const isEditMode = useSelector(getIsILLAEditMode);
  const selectedComponents = useSelector(getSelectedComponentDisplayNames);
  const executionResult = useSelector(getExecutionResult);
  const layoutInfoResult = useSelector(getClientWidgetLayoutInfo);
  const currentWidgetLayoutInfo: any = layoutInfoResult[displayName];
  const currentWidgetProps = get(executionResult, displayName, {});
  const isShownDot = useSelector(isShowDot);
  const isDraggingStateInGlobal = useSelector(getIsDragging);
  const shortcut = useContext(ShortCutContext)
  const isAutoLimitedMode =
    get(currentWidgetProps, `dynamicHeight`, "fixed") === "limited";

  const isSelected = useMemo(() => {
    return selectedComponents.some((currentDisplayName) => {
      return displayName === currentDisplayName;
    });
  }, [displayName, selectedComponents]);

  // const { handleMouseEnter, handleMouseLeave } = useMouseHover()
  const dispatch = useDispatch();
  const resizingIDs = useSelector(getResizingComponentIDs);
  const isResizingCurrent = resizingIDs.includes(displayName);
  const isGlobalResizing = resizingIDs.length > 0;
  const canDrag = widgetType !== "MODAL_WIDGET";
  const isGridCanvas = useSelector(getIsGridCanvas);
  const resizeDirection = useMemo(() => {
    const direction =
      currentWidgetProps.resizeDirection ??
      widgetBuilder(currentWidgetProps.$widgetType)?.config?.resizeDirection;
    return direction || RESIZE_DIRECTION.ALL;
  }, [currentWidgetProps.$widgetType, currentWidgetProps.resizeDirection]);

  const hoveredComponents = useSelector(getHoveredComponents);
  const isMouseOver =
    hoveredComponents[hoveredComponents.length - 1] === displayName;

  const isLikeProductionMode = useSelector(getIsLikeProductMode);
  const handleOnSelection = (e: MouseEvent<HTMLDivElement>) => {
    const rootState = store.getState();
    const isEditMode = getIsILLAEditMode(rootState);
    if (isGlobalResizing || !isEditMode) return;
    const displayNameMapDepth = getComponentDisplayNameMapDepth(rootState);
    const widgetExecutionLayoutInfo = getClientWidgetLayoutInfo(rootState);
    FocusManager.switchFocus("canvas", {
      displayName: displayName,
      type: "component",
      clickPosition: [],
    });
    trackInEditor(ILLA_MIXPANEL_EVENT_TYPE.SELECT, {
      element: "component",
      parameter1: "click",
    })
    e.stopPropagation();
    if (e.metaKey || e.shiftKey || e.ctrlKey) {
      let currentSelectedDisplayName = klona(selectedComponents);
      const index = currentSelectedDisplayName.findIndex(
        (currentDisplayName) => displayName === currentDisplayName
      );
      if (index !== -1) {
        currentSelectedDisplayName.splice(index, 1);
      } else {
        currentSelectedDisplayName.push(displayName);
      }

      const depths = currentSelectedDisplayName.map((displayName) => {
        return displayNameMapDepth[displayName];
      });
      const isEqual = depths.every((depth) => depth === depths[0]);
      if (!isEqual) {
        return;
      }
      if (currentSelectedDisplayName.length > 1) {
        const firstParentNode =
          widgetExecutionLayoutInfo[currentSelectedDisplayName[0]].parentNode;
        const isSameParentNode = currentSelectedDisplayName.every(
          (displayName) => {
            const parentNode =
              widgetExecutionLayoutInfo[displayName].parentNode;
            return parentNode === firstParentNode;
          }
        );
        if (!isSameParentNode) {
          const lastParentNode =
            widgetExecutionLayoutInfo[
              currentSelectedDisplayName[currentSelectedDisplayName.length - 1]
            ].parentNode;
          currentSelectedDisplayName = currentSelectedDisplayName.filter(
            (displayName) => {
              const currentParentNode =
                widgetExecutionLayoutInfo[displayName].parentNode;
              return lastParentNode === currentParentNode;
            }
          );
        }
      }
      currentSelectedDisplayName = Array.from(
        new Set(currentSelectedDisplayName)
      );
      dispatch(
        configActions.updateSelectedComponent(currentSelectedDisplayName)
      );
      return;
    }

    dispatch(configActions.updateSelectedComponent([displayName]));
  };

  const handleContextMenu = useCallback(
    (e: MouseEvent<HTMLDivElement>) => {
      
        shortcut.showDeleteDialog(selectedComponents, "widget", {
          source: "left_multi_delete",
        })
      
      FocusManager.switchFocus("canvas", {
        displayName: displayName,
        type: "component",
        clickPosition: [],
      });
      e.stopPropagation();
      dispatch(configActions.updateSelectedComponent([displayName]));
    },
    [displayName, dispatch,selectedComponents,shortcut]
  );
  console.log(handleContextMenu)
  const RenderComponets = ({ resizingObj1, gridContainer }) => {
    const resizingStyleObj2 = {
      isLikeProductionMode,
      isSelected,
      hasEditors: true,
      isHover: isMouseOver,
      isDragging: false,
      shownDot: isShownDot,
    };
    return (
      <Dropdown
      disabled={!isEditMode}
      position="right-start"
      
      trigger="contextmenu"
      dropList={
        <DropList
        //  w="184px"
         >
          <DropListItem
            value="duplicate"
            title={t("editor.context_menu.duplicate")}
            onClick={() => {
              CopyManager.copyComponentNodeByDisplayName([displayName])
              CopyManager.paste("duplicate")
            }}
          />
          <DropListItem
            deleted
            value="delete"
            title={t("editor.context_menu.delete")}
            onClick={() => {
              shortcut.showDeleteDialog([displayName], "widget", {
                source: "manage_delete",
              })
            }}
          />
        </DropList>
      }
      onVisibleChange={(visible) => {
        if (visible) {
          
          trackInEditor(ILLA_MIXPANEL_EVENT_TYPE.SHOW, {
            element: "component_management_canvas",
            parameter1: widgetType,
          })
        }
      }}
    >
      <div
        data-displayname={displayName}
        data-parentnode={parentNodeDisplayName}
        //  onMouseEnter={handleMouseEnter}
        //  onMouseLeave={handleMouseLeave}
        onClick={handleOnSelection}
        // onContextMenu={handleContextMenu}
        css={
          gridContainer
            ? resizingGridContainerStyle(resizingObj1, resizingStyleObj2)
            :
             resizingContainerStyle(resizingObj1, resizingStyleObj2)
        }
      >
        <DragContainer
          displayName={displayName}
          parentNodeDisplayName={parentNodeDisplayName}
          canDrag={canDrag}
          unitWidth={unitW}
          columnNumber={columnNumber}
        >
          {!isLikeProductionMode &&
            (isSelected || isMouseOver || isShownDot) && (
              <MoveBar
                isError={false}
                displayName={displayName}
                maxWidth={widgetWidth}
                widgetTop={widgetTop}
                widgetType={widgetType}
                userList={[]}
                columnNumber={columnNumber}
                gridContainer={gridContainer}
              />
            )}
          {isResizingCurrent ? (
            <div css={resizingPlaceholderStyle} />
          ) : (
            <>
              {children}
              {isEditMode &&
                isSelected &&
                !isDraggingStateInGlobal &&
                isAutoLimitedMode && (
                  <AutoHeightWithLimitedContainer
                    containerHeight={widgetHeight}
                    displayName={displayName}
                  />
                )}
            </>
          )}
        </DragContainer>
        {isSelected && !isLikeProductionMode && (
          <ResizeHandler
            resizeDirection={resizeDirection}
            displayName={displayName}
          />
        )}
      </div>
      </Dropdown>
    );
  };
  const rootExecutionProps = useSelector(getRootNodeExecutionResult)
  const bodySection = useSelector(getCurrentPageBodySection)
  const { style: bodyStyle } = bodySection ?? {}
  const { padding: bodyPadding = {} } = bodyStyle ?? {}
  const bodyPaddingSize = bodyPadding.size ?? `${BASIC_CANVAS_PADDING}`
  const { currentPageIndex, pageSortedKey } =
  rootExecutionProps
  const currentPageDisplayName = pageSortedKey[currentPageIndex]
  const canvasShape = useSelector(getCanvasShape);
  const sectionNodes = useSelector<RootState, ComponentMapNode[] | null>(
    (state) => {
      const components = getComponentMap(state)
      const currentPageNode = searchComponentFromMap(
        components,
        currentPageDisplayName,
      )
      if (!currentPageNode) return null
      return currentPageNode.childrenNode.map(
        (displayName) => components[displayName],
      )
    },
  )
  const panelsWidth = useMemo(()=>{
    let width = bodyPaddingSize*2+2;
     sectionNodes.map((e)=>{
      if(e.showName === "leftSection"){
       width = width+(canvasShape.canvasWidth*0.2)
      }else if(e?.showName === "rightSection"){
        width = width+ (canvasShape.canvasWidth*0.2)
      }
     })
    
     return width;
  },[sectionNodes,canvasShape.canvasWidth,bodyPaddingSize])

  return (
    <>
      {widgetType === "GridCONTAINER_WIDGET" && isGridCanvas ? (
        <RenderComponets
          gridContainer={true}
          resizingObj1={{
            width: canvasShape.canvasWidth-panelsWidth,
            height: widgetHeight,
            minWidth: DEFAULT_MIN_COLUMN * unitW,
            minHeight:
              (currentWidgetLayoutInfo?.layoutInfo.minH ?? 3) * UNIT_HEIGHT,
          }}
        />
      ) : (
        <PositionContainer
          x={widgetLeft}
          y={widgetTop}
          displayName={displayName}
        >
          <RenderComponets
            gridContainer={false}
            resizingObj1={{
              width: widgetWidth,
              height: widgetHeight,
              minWidth: DEFAULT_MIN_COLUMN * unitW,
              minHeight:
                (currentWidgetLayoutInfo?.layoutInfo.minH ?? 3) * UNIT_HEIGHT,
            }}
          />
        </PositionContainer>
      )}
    </>
  );
};
