import * as React from "react";
import { findComponentByType } from "@applicaster/zapp-react-native-utils/pluginUtils";
import { useIsRTL } from "@applicaster/zapp-react-native-utils/localizationUtils";

import { CellRendererResolver } from "../CellRendererResolver";

import { componentsLogger } from "../../Helpers/logger";

type Decorator = (arg: React.ComponentType<any>) => React.ComponentType<any>;

type Props = {
  component: any;
  components: Record<string, React.ComponentType<any>>;
  children: any;
  decorators?: Decorator | Decorator[];
  plugins: [{ module: any; type: string; name: string }];
  styles: any;
  cellStyles: any;
};

const logger = componentsLogger.addSubsystem("ComponentResolver");

export function ComponentResolver({
  component,
  components,
  decorators,
  children,
  plugins,
  styles,
  cellStyles,
}: Props) {
  const { component_type } = component;
  const isRTL = useIsRTL();

  const Component = React.useMemo(
    () =>
      findComponentByType({
        components,
        componentType: component_type,
        // @ts-ignore
        decorators,
        plugins,
      }),
    []
  );

  const CellRenderer = React.useMemo(
    () =>
      CellRendererResolver({
        component,
        plugins,
        styles,
        cellStyles,
        isRTL,
      }),
    []
  );

  if (!Component) {
    logger.warning({
      message: `Component ${component_type} cannot be found - it is skipped from rendering`,
    });

    return null;
  }

  return children(Component, CellRenderer);
}

export const ComponentResolverComponent = React.memo<Props>(ComponentResolver);
