import Grid2 from "@mui/material/Unstable_Grid2/Grid2";
import { FC, useCallback, useEffect, useMemo, useRef } from "react";
import RenderChildrenCanvas from "../RenderChildrenCanvas";
import {
  ContainerEmptyState,
  // GridConfigTemp,
} from "../ContainerWidget/emptyState";
import { ContainerProps } from "../ContainerWidget/interface";
// import { Box } from "@mui/material";
import { applyContainerWrapperStyle } from "../ContainerWidget/style";
import { Tooltip } from "@mui/material";
import { getIsILLAEditMode } from "@/redux/config/configSelector";
import { useSelector } from "react-redux";

const GridContainer: FC<ContainerProps> = (props) => {
  const {
    currentIndex,
    updateComponentRuntimeProps,
    // deleteComponentRuntimeProps,
    viewList,
    tooltipText,
    childrenNode,
    columnNumber,
    dynamicHeight = "auto",
    triggerEventHandler,
    updateComponentHeight,
    linkWidgetDisplayName,
    // padding,
    displayName,
    handleUpdateMultiExecutionResult,
    justifyContent,
  } = props;
  const preCurrentViewIndex = useRef<number>(currentIndex);
  const isEditMode = useSelector(getIsILLAEditMode);
  useEffect(() => {
    if (typeof preCurrentViewIndex.current !== "number") {
      preCurrentViewIndex.current = currentIndex;
    }
    if (preCurrentViewIndex.current !== currentIndex) {
      triggerEventHandler("change");
      preCurrentViewIndex.current = currentIndex;
    }
  }, [currentIndex, triggerEventHandler]);

  //   const handleOnClick = useCallback(() => {
  //     triggerEventHandler("click");
  //   }, [triggerEventHandler]);

  const enableAutoHeight = useMemo(() => {
    switch (dynamicHeight) {
      case "auto":
        return true;
      case "limited":
        return true;
      case "fixed":
      default:
        return false;
    }
  }, [dynamicHeight]);

  const handleUpdateHeight = useCallback(
    (height: number) => {
      if (!updateComponentHeight || !enableAutoHeight) return;
      updateComponentHeight(height + 2);
    },
    [enableAutoHeight, updateComponentHeight]
  );

  const handleUpdateOriginalDSLAttrs = useCallback(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (updateSlice: Record<string, any>) => {
      handleUpdateMultiExecutionResult([
        {
          displayName,
          value: updateSlice,
        },
      ]);
      if (linkWidgetDisplayName && linkWidgetDisplayName.length > 0) {
        const curUpdateSlice = linkWidgetDisplayName.map((name) => ({
          displayName: name,
          value: updateSlice,
        }));

        handleUpdateMultiExecutionResult(curUpdateSlice);
      }
    },
    [displayName, handleUpdateMultiExecutionResult, linkWidgetDisplayName]
  );

  useEffect(() => {
    updateComponentRuntimeProps?.({
      setCurrentViewKey: (key: string) => {
        const index = viewList.findIndex((viewItem) => viewItem.key === key);
        if (index === -1) return;
        handleUpdateOriginalDSLAttrs({
          currentIndex: index,
          currentKey: key,
        });
      },
      setCurrentViewIndex: (index: string) => {
        const numberIndex = parseInt(index);
        const view = viewList[numberIndex];
        if (!view) return;
        handleUpdateOriginalDSLAttrs({
          currentIndex: numberIndex,
          currentKey: view.key,
        });
      },
      showNextView: (loop: boolean) => {
        let newCurrentIndex = currentIndex + 1;
        if (newCurrentIndex >= viewList.length) {
          if (!loop) return;
          newCurrentIndex = 0;
        }
        const currentView = viewList[newCurrentIndex];
        handleUpdateOriginalDSLAttrs({
          currentIndex: newCurrentIndex,
          currentKey: currentView.key,
        });
      },
      showNextVisibleView: (loop: boolean) => {
        let newCurrentIndex = currentIndex + 1;
        if (newCurrentIndex >= viewList.length) {
          if (!loop) return;
          newCurrentIndex = 0;
        }
        let currentView = viewList[newCurrentIndex];
        while (currentView.hidden || currentView.disabled) {
          newCurrentIndex++;
          currentView = viewList[newCurrentIndex];
          if (newCurrentIndex >= viewList.length) {
            if (!loop) return;
            newCurrentIndex = 0;
          }
        }
        handleUpdateOriginalDSLAttrs({
          currentIndex: newCurrentIndex,
          currentKey: currentView.key,
        });
      },
      showPreviousView: (loop: boolean) => {
        let newCurrentIndex = currentIndex - 1;

        if (newCurrentIndex < 0) {
          if (!loop) return;
          newCurrentIndex = viewList.length - 1;
        }
        const currentView = viewList[newCurrentIndex];
        handleUpdateOriginalDSLAttrs({
          currentIndex: newCurrentIndex,
          currentKey: currentView.key,
        });
      },
      showPreviousVisibleView: (loop: boolean) => {
        let newCurrentIndex = currentIndex - 1;

        if (newCurrentIndex < 0) {
          if (!loop) return;
          newCurrentIndex = viewList.length - 1;
        }
        let currentView = viewList[newCurrentIndex];
        while (currentView.hidden || currentView.disabled) {
          newCurrentIndex--;
          currentView = viewList[newCurrentIndex];
          if (newCurrentIndex < 0) {
            if (!loop) return;
            newCurrentIndex = viewList.length - 1;
          }
        }
        handleUpdateOriginalDSLAttrs({
          currentIndex: newCurrentIndex,
          currentKey: currentView.key,
        });
      },
    });
    // return () => {
    //   deleteComponentRuntimeProps()
    // }
  }, [
    // deleteComponentRuntimeProps,
    updateComponentRuntimeProps,
    handleUpdateOriginalDSLAttrs,
    viewList,
    currentIndex,
  ]);
  const handleOnClick = useCallback(() => {
    triggerEventHandler("click");
  }, [triggerEventHandler]);
  return (
    <Tooltip title={tooltipText}>
      <Grid2 container justifyContent={justifyContent || "center"} xs={12}>
        {viewList.map((e, i) => {
          return (
            <>
              <Grid2
                xs={e.xs}
                sm={e.sm}
                md={e.md}
                lg={e.lg}
                key={e.id}
                sx={{ position: "relative" ,border:isEditMode?"1px dotted gray":"none",}}
                justifyContent={"center"}
                css={applyContainerWrapperStyle}
                // onClick={()=> alert(canvasId?childrenNode[i+canvasId*3]:childrenNode[i])}
              >
                <div css={applyContainerWrapperStyle} onClick={handleOnClick}>
                  {isEditMode && (
                    <div
                      style={{
                        position: "absolute",
                        top: 2,
                         zIndex:"10",
                        borderRadius:"5px",
                        right: 0,
                        fontSize: "10px",
                        background:"#654aec",
                        color:"white",
                        padding:"2px 5px"
                      }}
                    >
                      {childrenNode[i]}
                    </div>
                  )}
                  {Array.isArray(childrenNode) &&
                  currentIndex < childrenNode.length ? (
                    <RenderChildrenCanvas
                      displayName={childrenNode[i]}
                      columnNumber={columnNumber}
                      handleUpdateHeight={handleUpdateHeight}
                      canResizeCanvas={enableAutoHeight}
                      containerPadding={"0px"}
                    />
                  ) : (
                    <ContainerEmptyState />
                  )}
                </div>
              </Grid2>
            </>
          );
        })}
      </Grid2>
    </Tooltip>
  );
};

export default GridContainer;
