/* eslint-disable @typescript-eslint/no-explicit-any */
import { useDrop } from "react-dnd";
import RenderChildrenCanvas from "../RenderChildrenCanvas";
import { ContainerEmptyState } from "../ContainerWidget/emptyState";
import { memo, useCallback, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  getIsIMPAKTEditMode,
  getSelectedScreen,
} from "@/redux/config/configSelector";
import { configActions } from "@/redux/config/configSlice";
import { convertStyles, RowContent } from "./utils";
import { componentsActions } from "@/redux/currentApp/components/componentsSlice";
import { gridItemStyle } from "./style";
import _ from "lodash";
import { getStyleMap } from "@/utils/getStyleMap";
import { isCurrentNodeDisable } from "@/redux/currentApp/components/componentsSelector";
import { DragInfo } from "@/page/App/components/scaleSquare/components/DragContainer/interface";
import { DropCollectedProps } from "@/page/App/components/dotPanel/components/Canvas/interface";
import { css } from "@emotion/react";
import { useTheme } from "@mui/material";
import store, { RootState } from "@/store";
const GridChild = memo(function ({
  config,
  configArray,
  childrenNode,
  index,
  handleAddNewRow,
  context,
  attrPath,
  handleUpdateOriginalDSLMultiAttr,
}: any) {
  const isEditMode = useSelector(getIsIMPAKTEditMode);
  const [menuPosition, setMenuPosition] = useState({ top: 0, left: 0 });
  const [modalVisible, setModalVisible] = useState(false);
   
  const dispatch = useDispatch();
  const Screen = useSelector(getSelectedScreen);
  const theme = useTheme()
  const handleDeleteOptionItem = useCallback(
    (index: number) => {
      if (configArray.length <= 1) return;
      const updatedArray = configArray.filter(
        (_optionItem: Record<string, any>, i: number) => {
          return i !== index;
        }
      );
      const currentChildrenNodeDisplayName = childrenNode[index];
      const updateSlice = {
        [attrPath]: updatedArray,
      };
      handleUpdateOriginalDSLMultiAttr?.(updateSlice);
      dispatch(
        componentsActions.deleteComponentNodeReducer({
          displayNames: [currentChildrenNodeDisplayName],
        })
      );
    },
    [
      attrPath,
      childrenNode,
      configArray,
      dispatch,
      handleUpdateOriginalDSLMultiAttr,
    ]
  );
  const setModelVisibilityFalse = () => {
    if (isEditMode && modalVisible) {
      setModalVisible(false);
    }
  };
  const [, drop] = useDrop<DragInfo, any, DropCollectedProps>(
    () => ({
      accept: "GRID",
      collect: (monitor) => {
        return {
          isOver: monitor.isOver({ shallow: true }),
        };
      },
      drop(dropItem: any) {
        if (!dropItem) {
          return;
        }
        if (dropItem.type == "undraggableComponents") {
          return;
        }
        if (dropItem.type === "Components") {
          const { draggedComponents } = dropItem;
          const updateSlices = [
            {
              displayName: draggedComponents[0].displayName,
              x: -1,
              y: -1,
              w: 2,
              h: 5,
            },
          ];
          dispatch(
            componentsActions.updateComponentPositionReducer({
              oldParentNodeDisplayName: draggedComponents[0].parentNode,
              newParentNodeDisplayName: config.displayName,
              updateSlices,
              columnNumberWhenDrag: 1,
              columnNumberWhenDrop: 1,
            })
          );
          return;
        }
        const cloneConfig = _.cloneDeep(configArray);
        const formatedData = cloneConfig.map((e) => {
          if (e.displayName === dropItem.displayName) {
            return config.displayName;
          } else if (e.displayName === config.displayName) {
            return dropItem.displayName;
          }
          return e.displayName;
        });
        dispatch(
          componentsActions.sortComponentNodeChildrenReducer({
            parentDisplayName: config.parentNode,
            newChildrenNode: formatedData,
          })
        );
      },
    }),
    [configArray]
  );
  const userGivenStyle = useMemo(() => {
    function getScrenCSS(CurrentScreen) {
      return convertStyles(
        getStyleMap(
          config?.props?.[CurrentScreen]?.trueClasses ?? [],
          config?.props?.[CurrentScreen]?.falseClasses ?? [],
          config?.props?.isClassTrue ?? true,
          context
        ) || []
      );
    }
    const desktopCSS = getScrenCSS(isEditMode ? Screen : "Desktop");
    const mobileCSS = getScrenCSS("Mobile");
    const tabletCSS = getScrenCSS("Tablet");
    return css`
      ${desktopCSS} /* Default styles for desktop */
  
    @media (max-width: 1024px) {
        ${tabletCSS}/* Styles for tablet */
      }

      @media (max-width: 768px) {
        ${mobileCSS}/* Styles for mobile */
      }
    `;
  }, [Screen, config?.props, context, isEditMode]);
  const isDisabled = false;
  //isCurrentNodeDisable(config.displayName);

  return (
    <div
      key={`gridChildWrppaer-${config.displayName}`}
      css={gridItemStyle(config, context, Screen, isEditMode,theme)}
      onContextMenu={(event) => {
        if (isEditMode) {
          event.preventDefault();
          event.stopPropagation();
          setModalVisible((pre) => !pre);
          setMenuPosition({ top: event.clientY, left: event.clientX });
        }
      }}
      onBlur={setModelVisibilityFalse}
      onMouseLeave={setModelVisibilityFalse}
      onPointerLeave={setModelVisibilityFalse}
    >
      {modalVisible && isEditMode && !isDisabled && (
        <div
          style={{
            position: "fixed",
            zIndex: 30,
            background: "white",
            color: "black",
            textAlign: "left",
            boxShadow: "2px 2px 5px gray",
            borderRadius: "5px",
            left: menuPosition.left - 20,
            top: menuPosition.top,
            fontSize: "14px",
            paddingTop: "10px",
            fontFamily: "roboto",
          }}
        >
          <RowContent
            click={(e) => handleAddNewRow("Row", childrenNode.length, e)}
            error={false}
            
            setModalVisible={setModalVisible}
            rowContent="Add Row On Bottom"
          />
          <RowContent
            click={(e) => handleAddNewRow("Row", 0, e)}
            setModalVisible={setModalVisible}
            error={false}
            rowContent="Add Row On Top"
          />
          <RowContent
            click={(e) => handleAddNewRow("Div", index, e)}
            setModalVisible={setModalVisible}
            error={false}
            rowContent="Add Div On Right"
          />
          <RowContent
            click={(e) => handleAddNewRow("Div", index, e)}
            setModalVisible={setModalVisible}
            error={false}
            rowContent="Add Div On Left"
          />
          <RowContent
            click={(e) => {
              e.stopPropagation();
              handleDeleteOptionItem(index);
            }}
            error={true}
            setModalVisible={setModalVisible}
            rowContent="Delete Div"
          />
        </div>
      )}

      <div
        key={config.displayName}
        ref={drop}
        onClick={(e) => {
          e.stopPropagation();
          if (!isCurrentNodeDisable(config.displayName,store.getState() as RootState)) {
            dispatch(
              configActions.updateSelectedComponent([config.displayName])
            );
          }
        }}
        style={{
          textAlign: "center",
          cursor: "grab",
          position: "relative",
        }}
      >
        {isEditMode && (
          <div
          key={`${config.displayName}-displayName`}
            // ref={ drag}
            role="DraggableBox"
            style={{
              position: "absolute",
              zIndex: 1,
              bottom: 1,
              right: 0,
              fontSize: "8px",
              background: theme.palette.action.focus,
              color:theme.palette.text.primary,
              padding: "3px",
              borderRadius:"1px"
            }}
          >
            {config.displayName}
          </div>
        )}

        <div
          key={config.displayName + "CannvasWrappper"}
          css={userGivenStyle}
          // style={{background:"transparent"}}
        >
          {Array.isArray(childrenNode) ? (
            <RenderChildrenCanvas
              displayName={childrenNode[index]}
              columnNumber={1}
              handleUpdateHeight={() => {}}
              canResizeCanvas={false}
              containerPadding={"1px"}
              key={config.displayName + "canvas"}
              gridContainer={true}
            />
          ) : (
            isEditMode && (
              <ContainerEmptyState
                rowCount={config?.props?.[Screen]?.rowSpan || "1"}
              />
            )
          )}
        </div>
      </div>
    </div>
  );
});

export default GridChild;
