import * as React from "react";
import { StyleSheet, Text } from "react-native";
import { useState, useRef, useEffect } from "react";

export type BlocksWrapperProps = {
  blocks: BuilderBlock[] | undefined;
  parent: string | undefined;
  path: string | undefined;
  styleProp: Record<string, any> | undefined;
  /**
   * The element that wraps each list of blocks. Defaults to a `div` element ('ScrollView' in React Native).
   */
  BlocksWrapper: any;
  /**
   * Props to be applied to the wrapping element of blocks. Can be set in two ways:
   * 1. Globally via `<Content blocksWrapperProps={{...}}/>` - applies to all blocks wrappers in the Content
   * 2. Locally via `<Blocks BlocksWrapperProps={{...}}/>` - applies only to this specific blocks instance and overrides global props
   *
   * For merging both global and local props, spread the context props before adding your own:
   * ```
   * <Blocks
   *   BlocksWrapperProps={{
   *     ...builderContext.BlocksWrapperProps,
   *     'data-test-id': 'my-test-id'
   *   }}
   * />
   * ```
   */
  BlocksWrapperProps: any;
  children?: any;
  classNameProp?: string;
};
import { isEditing } from "../../functions/is-editing";
import type { BuilderBlock } from "../../types/builder-block";

function BlocksWrapper(props: BlocksWrapperProps) {
  const blocksWrapperRef = useRef<HTMLDivElement>(null);
  const [shouldUpdate, setShouldUpdate] = useState(() => false);

  function className() {
    return [
      "builder-blocks",
      !props.blocks?.length ? "no-blocks" : "",
      props.classNameProp,
    ]
      .filter(Boolean)
      .join(" ");
  }

  function dataPath() {
    if (!props.path) {
      return undefined;
    }
    const thisPrefix = "this.";
    const pathPrefix = "component.options.";
    return props.path.startsWith(thisPrefix)
      ? props.path.replace(thisPrefix, "")
      : props.path.startsWith(pathPrefix)
      ? props.path
      : `${pathPrefix}${props.path || ""}`;
  }

  function onClick() {
    if (isEditing() && !props.blocks?.length) {
      window.parent?.postMessage(
        {
          type: "builder.clickEmptyBlocks",
          data: {
            parentElementId: props.parent,
            dataPath: dataPath(),
          },
        },
        "*"
      );
    }
  }

  function onMouseEnter() {
    if (isEditing() && !props.blocks?.length) {
      window.parent?.postMessage(
        {
          type: "builder.hoverEmptyBlocks",
          data: {
            parentElementId: props.parent,
            dataPath: dataPath(),
          },
        },
        "*"
      );
    }
  }

  useEffect(() => {
    if (isEditing()) {
      /**
       * React Native strips off custom HTML attributes, so we have to manually set them here
       * to ensure that blocks are correctly dropped into the correct parent.
       */
      if (dataPath()) {
        blocksWrapperRef.current.setAttribute("builder-path", dataPath());
      }
      if (props.parent) {
        blocksWrapperRef.current.setAttribute(
          "builder-parent-id",
          props.parent
        );
      }
    }
  }, []);
  useEffect(() => {}, [props.blocks]);

  return (
    <props.BlocksWrapper
      ref={blocksWrapperRef}
      builder-path={dataPath()}
      builder-parent-id={props.parent}
      {...{
        dataSet: {
          class: className(),
        },
      }}
      style={{
        ...styles.propsBlocksWrapper1,
        ...props.styleProp,
      }}
      onClick={(event) => onClick()}
      onMouseEnter={(event) => onMouseEnter()}
      onKeyPress={(event) => onClick()}
      {...props.BlocksWrapperProps}
    >
      {props.children}
    </props.BlocksWrapper>
  );
}

const styles = StyleSheet.create({
  propsBlocksWrapper1: { display: "flex", flexDirection: "column" },
});

export default BlocksWrapper;
