import * as React from "react";
import { FlatList, Text } from "react-native";
import { useContext } from "react";
import BuilderContext from "../../context/builder.context";
import ComponentsContext from "../../context/components.context";
import Block from "../block/block";
import BlocksWrapper from "./blocks-wrapper";
import type { BlocksProps } from "./blocks.types";
import { memo } from "react";

function Blocks(props: BlocksProps) {
  const builderContext = useContext(BuilderContext);

  const componentsContext = useContext(ComponentsContext);

  const renderItem = React.useCallback(
    ({ item }: { item: any }) => (
      <Block
        block={item}
        linkComponent={props.linkComponent}
        context={props.context || builderContext}
        registeredComponents={
          props.registeredComponents || componentsContext?.registeredComponents
        }
      />
    ),
    [
      props.linkComponent,
      props.context,
      props.registeredComponents,
      builderContext,
      componentsContext?.registeredComponents,
    ]
  );

  // Memoize keyExtractor
  const keyExtractor = React.useCallback((item: any) => item.id.toString(), []);

  return (
    <BlocksWrapper
      blocks={props.blocks}
      parent={props.parent}
      path={props.path}
      styleProp={props.styleProp}
      BlocksWrapperProps={
        props.BlocksWrapperProps ||
        props.context?.BlocksWrapperProps ||
        builderContext?.BlocksWrapperProps
      }
      classNameProp={props.className}
      BlocksWrapper={
        props.context?.BlocksWrapper || builderContext?.BlocksWrapper
      }
    >
      {props.children}
      {props.blocks ? (
        <FlatList
          data={props.blocks}
          renderItem={renderItem}
          keyExtractor={keyExtractor}
          removeClippedSubviews
          maxToRenderPerBatch={10}
          windowSize={5}
          initialNumToRender={5}
        />
      ) : null}
    </BlocksWrapper>
  );
}

export default memo(Blocks);
