import { get } from "lodash-es";
import { FC, memo, useCallback, useMemo, MouseEvent } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  getIsIMPAKTEditMode,
  getSelectedComponentDisplayNames,
} from "@/redux/config/configSelector";
import {
  getExecutionError,
  getExecutionResult,
} from "@/redux/currentApp/executionTree/executionSelector";
import { WrapperContainerProps } from "./interface";
import { applyWrapperPendingStyle, hoverHotSpotStyle } from "./style";
import { configActions } from "@/redux/config/configSlice";

const WrapperContainer: FC<WrapperContainerProps> = (props) => {
  const { displayName, parentNodeDisplayName, widgetHeight, children } = props;
  const executionResult = useSelector(getExecutionResult);

  const selectedComponents = useSelector(getSelectedComponentDisplayNames);
  const isEditMode = useSelector(getIsIMPAKTEditMode);
  const errors = useSelector(getExecutionError);
  const dispatch = useDispatch();
  const isSelected = useMemo(() => {
    return selectedComponents.some((currentDisplayName) => {
      return displayName === currentDisplayName;
    });
  }, [displayName, selectedComponents]);

  const realProps: Record<string, any> = get(executionResult, displayName, {});

  const hasError = useMemo(() => {
    const widgetErrors = errors[displayName] ?? {};
    return Object.keys(widgetErrors).length > 0;
  }, [displayName, errors]);
  const isAutoLimitedMode = realProps?.dynamicHeight === "limited";
  const isOverLap =
    isAutoLimitedMode &&
    (realProps?.dynamicMaxHeight === widgetHeight ||
      realProps?.dynamicMinHeight === widgetHeight);
  const handleOnSelection = useCallback(
    (e: MouseEvent<HTMLDivElement>) => {
      if (!isEditMode) return;
      e.stopPropagation();
      dispatch(configActions.updateSelectedComponent([displayName]));
    },
    [dispatch, displayName, isEditMode]
  );
  return (
    <div
      css={hoverHotSpotStyle}
      data-displayname={displayName}
      data-parentnode={parentNodeDisplayName}
      onClick={handleOnSelection}
    >
      <div
        css={applyWrapperPendingStyle({
          hasError,
          isSelected,
          isEditor: isEditMode,
          isLimitedModeAndOverLap: isOverLap,
        })}
      >
        {children}
      </div>
    </div>
  );
};

WrapperContainer.displayName = "WrapperContainer";

export default memo(WrapperContainer);
