import React, { useCallback, useMemo, useState } from "react";
import { Platform, View, ViewStyle, Text } from "react-native";
import { v4 as uuidv4 } from "uuid";
import { ComponentProps, ConfigItem } from "./interface";
import { useDrop } from "react-dnd";
import { DRAG_EFFECT, DragInfo } from "@/page/App/components/scaleSquare/components/DragContainer/interface";
import { DropCollectedProps, DropResultInfo } from "@/page/App/components/dotPanel/components/Canvas/interface";
import useMeasure from "react-use-measure";
import RenderComponentCanvasContainer from "@/page/App/components/dotPanel/components/Canvas/renderComponentCanvasContainer";
import RenderComponentCanvasContainerMobile from "@/page/App/components/dotPanel/components/Canvas/renderComponentCanvasContainerMobile";
import { getIsIMPAKTEditMode, getIsIMPAKTProductMode } from "@/redux/config/configSelector";
import { getCurrentPageBodySection } from "@/redux/currentApp/executionTree/executionSelector";
import { getCurrentDisplayName } from "@/page/App/components/dotPanel/hooks/sectionUtils";
import RenderChildrenCanvas from "../RenderChildrenCanvas";
import { getComponentMap } from "@/redux/currentApp/executionTree/executionSelector";
import { configActions } from "@/redux/config/configSlice";
import { useDispatch, useSelector } from "react-redux";
import { isCurrentNodeDisable } from "@/redux/currentApp/components/componentsSelector";
import { css } from "@emotion/native";
import { RowContent } from "../CSSGrid/utils";
import { componentsActions } from "@/redux/currentApp/components/componentsSlice";
import { getStyleMap } from "@/utils/getStyleMap";
import { NativeChild } from "./NativeChild";


// interface ViewComponentProps extends ComponentProps {
//   isEditMode?: boolean;
//   childrenNode?: ConfigItem[];
//   currentIndex?: number;
//   handleOnClick?: () => void;
//   handleUpdateHeight?: () => void;
//   RenderChildrenCanvas?: React.FC<any>;
//   ContainerEmptyState?: React.FC;
//   isGridContainer?: boolean;
// }

export const NativeContainer: React.FC<any> = (props) => {


  const
    {
      direction,
      style,
      justify,
      align,
      padding,
      rowGap,
      columnGap,
      //   isEditMode,
      //   childrenNode,
      //   currentIndex = 0,
      //   handleOnClick,
      //   handleUpdateHeight,
      //   RenderChildrenCanvas,
      //   ContainerEmptyState,
      //   isGridContainer,
      childrenNode,
      displayName,
      isClassTrue = true,
      trueClasses = [],
      falseClasses = [],
      context

    } = props
  console.log("props >> ", props);
  const isEditMode = useSelector(getIsIMPAKTEditMode);
  const [modalVisible, setModalVisible] = useState(false);
  const [menuPosition, setMenuPosition] = useState({ top: 0, left: 0 });
  const containerStyle: ViewStyle = {
    flexDirection: direction === "row" ? "row" : "column",
    justifyContent: justify,
    alignItems: align,
    padding,
    rowGap: rowGap,
    columnGap: columnGap,
    // height: "90%",
    // width: "100%",
    flex: 1,
    ...style,
  };
  const containerNameStyle: ViewStyle = {
    position: 'absolute',
    left: 0,
    bottom: 0,
    zIndex: 5,
    backgroundColor: '#E2EAF4',
    borderWidth: 0.5,
    borderColor: '#9793FD' ,
    // borderColor: Platform.OS === 'web' ? '#9793FD' : "none",
    borderStyle: 'dotted',
    padding: 2,
    width: 50,   // Set a smaller width
    height: 10,

    // flexShrink: 1
  };
  

  const styles = useMemo(() => {
    return getStyleMap(trueClasses, falseClasses, isClassTrue, context);
  }, [trueClasses, falseClasses, isClassTrue, context]);

  console.log("styles", styles);
  const flattenedStyles = Array.isArray(styles)
  ? styles.flat().reduce((merged, styleObj) => ({ ...merged, ...styleObj }), {})
  : styles || {};


  const dispatch = useDispatch();

  const componentsMap: any = useSelector(getComponentMap);
  const ChildNodesMap = useMemo(
    () =>
      componentsMap[displayName].childrenNode.map((e) => {
        return componentsMap[e];
      }),
    [componentsMap, displayName]
  );

  const handleDeleteOptionItem: any = useCallback(
    (index: number) => {
      const updatedArray = ChildNodesMap.filter((_optionItems: Record<string, any>, i: number) => {
        return i !== index;
      })
      const currentChildrenNodeDisplayName = childrenNode[index];
      const updateSlice = {
        [props.attrPath]: updatedArray,
      };
      props.handleUpdateOriginalDSLMultiAttr?.(updateSlice);
      dispatch(
        componentsActions.deleteComponentNodeReducer({
          displayNames: [currentChildrenNodeDisplayName],
        })
      );

    }, [childrenNode, props.attrPath, ChildNodesMap, dispatch, props.handleUpdateOriginalDSLMultiAttr]
  )

  console.log("ChildNodesMap >> ", ChildNodesMap);

  return (

    <View
      key={displayName}
      // ref={Platform.OS === 'web' ? dropRef: null}
      style={{...flattenedStyles,...containerStyle}}

    >
      {
        Platform.OS === 'web' &&
        <View style={containerNameStyle}>
          <Text style={{ fontSize: 5.5 }}>{displayName}</Text>
        </View>
      }


      {
        childrenNode && childrenNode.length > 0 ? (
          ChildNodesMap.map((children: any, index: number) =>

          (
            <NativeChild
              key={children.displayName}
              children={children}
              index={index}
              dispatch={dispatch}
              modalVisible={modalVisible}
              menuPosition={menuPosition}
              setModalVisible={setModalVisible}
              handleDeleteOptionItem={handleDeleteOptionItem}
              context={context}
            />
          ))
        ) : (
          <RenderChildrenCanvas
            displayName={displayName}
            columnNumber={1}
            handleUpdateHeight={() => { }}
            canResizeCanvas={false}
            containerPadding={"1px"}
            key={displayName + "Nativecanvas"}
            gridContainer={true}
          />
        )
      }
    </View>
  );
};

