/* eslint-disable @typescript-eslint/no-explicit-any */
import { FC, useCallback, useMemo } from "react";
import { ContainerProps } from "../ContainerWidget/interface";
import { useDispatch, useSelector } from "react-redux";
import { v4 } from "uuid";
import GridChild from "./GridChild";
import { newGenerateChildrenComponentNode } from "@/utils/generators/generateComponentNode";
import { BasicContainerConfig } from "../BasicContainer/BasicContainer";
import { componentsActions } from "@/redux/currentApp/components/componentsSlice";
import { getComponentMap } from "@/redux/currentApp/executionTree/executionSelector";
import _ from "lodash";
import {
  getIsIMPAKTEditMode,
  getSelectedScreen,
} from "@/redux/config/configSelector";
import { gridDisplayNameCss, gridStyle } from "./style";
import { getStyleMap } from "@/utils/getStyleMap";
import { convertStyles } from "./utils";
import { css } from "@emotion/react";
import { useTheme } from "@mui/material";
const CSSGrid: FC<ContainerProps | any> = (props) => {
  const {
    Mobile = {
      columnSize: "1",
      columnFraction: ["1fr"],
      columnGap: 1,
      trueClasses: [],
      falseClasses: [],
    },
    context,
    Tablet = {
      columnSize: "3",
      columnFraction: ["1fr", "1fr", "1fr"],
      gridGap: 1,
      trueClasses: [],
      falseClasses: [],
    },
    Desktop = {
      columnSize: "4",
      columnFraction: ["1fr", "1fr", "1fr", "1fr"],
      gridGap: 1,
      trueClasses: [],
      falseClasses: [],
    },
    handleUpdateOriginalDSLMultiAttr,
    childrenNode,
    displayName,
    isClassTrue = true,
  } = props;
  const theme = useTheme()
  const Screen: any = useSelector(getSelectedScreen);
  const isEditMode: any = useSelector(getIsIMPAKTEditMode);
  const componentsMap: any = useSelector(getComponentMap);
  const ChildNodesMap = useMemo(
    () =>
      componentsMap[displayName].childrenNode.map((e) => {
        return componentsMap[e];
      }),
    [componentsMap, displayName]
  );
  const dispatch = useDispatch();
  const handleAddNewRow = useCallback(
    (ComponentName, componentIndex, e) => {
      e.stopPropagation();
      const componentActualCount: number =
        ComponentName === "Row" ? Desktop.columnSize || 4 : 1;
      const newItem = [];
      for (let i = 0; i < componentActualCount; i++) {
        newItem.push({
          id: v4(),
          key: `view ${childrenNode.length + 1 + i}`,
          label: `view ${childrenNode.length + +1 + i}`,
          rowSpan: 1,
          columnSpan: 1,
        });
      }
      const previosArr = [];
      const arr1 = [];
      newItem.map((e: any) => {
        const newChildrenNodes = newGenerateChildrenComponentNode(
          BasicContainerConfig,
          displayName
        );
        handleUpdateOriginalDSLMultiAttr?.({
          ["viewList"]: [...ChildNodesMap, ...previosArr, e],
        });
        previosArr.push(e);
        arr1.push(newChildrenNodes);
      });
      dispatch(componentsActions.addComponentReducer(arr1));
      const childNodesArray = _.cloneDeep(childrenNode);
      const newChilds: string[] = arr1.map((e) => e.displayName);
      childNodesArray.splice(componentIndex, 0, ...newChilds);
      dispatch(
        componentsActions.sortComponentNodeChildrenReducer({
          parentDisplayName: displayName,
          newChildrenNode: childNodesArray,
        })
      );
    },
    [
      Desktop.columnSize,
      dispatch,
      childrenNode,
      displayName,
      handleUpdateOriginalDSLMultiAttr,
      ChildNodesMap,
    ]
  );

  const containerSTyle = useMemo(() => {
    return gridStyle(Mobile, Tablet, Desktop, Screen, isEditMode,theme);
  }, [Desktop, Mobile, Screen, Tablet, isEditMode, theme]);

  // const userGivenStyle = useMemo(() => {
  //   const allDisplay = {Desktop, Mobile, Tablet}
  //   return getStyleMap(allDisplay[Screen].trueClasses, allDisplay[Screen].falseClasses, isClassTrue, context);
  // }, [Desktop, Mobile, Screen,Tablet, isClassTrue, context]);

  const userGivenStyle = useMemo(() => {
    function getScrenCSS(CurrentScreen) {
      const allDisplay = { Desktop, Mobile, Tablet };
      return convertStyles(
        getStyleMap(
          allDisplay?.[CurrentScreen]?.trueClasses ?? [],
          allDisplay?.[CurrentScreen]?.falseClasses ?? [],
          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 */
      }
    `;
  }, [Desktop, Mobile, Screen, Tablet, context, isClassTrue, isEditMode]);
  return (
    <div css={[containerSTyle, userGivenStyle]} key={displayName}>
      {isEditMode && (
        <div css={[gridDisplayNameCss(theme), userGivenStyle]}>{displayName}</div>
      )}
      {ChildNodesMap.map((gridChildConfig: any, i: number) => {
        return (
          <GridChild
            context={context}
            config={gridChildConfig || {}}
            configArray={ChildNodesMap}
            index={i}
            handleAddNewRow={handleAddNewRow}
            childrenNode={props.childrenNode}
            attrPath={props.attrPath}
            handleUpdateOriginalDSLMultiAttr={
              props.handleUpdateOriginalDSLMultiAttr
            }
          />
        );
      })}
    </div>
  );
};
export default CSSGrid;
