/// <reference types="@applicaster/applicaster-types" />
/// <reference types="@applicaster/zapp-react-native-ui-components" />
import React from "react";
import { useRoute } from "@applicaster/zapp-react-native-utils/reactHooks/navigation";
import { usePickFromState } from "@applicaster/zapp-react-native-redux/hooks";
import { ZappPipesSearchContext } from "@applicaster/zapp-react-native-ui-components/Contexts";
import { useScreenContext } from "@applicaster/zapp-react-native-utils/reactHooks/screen/useScreenContext";
import { ResolverSelector } from "./ResolverSelector";
import { ComponentDataSourceContext } from "./types";

type Props = {
  component: ZappUIComponent;
  feedUrl?: string;
  riverId: string;
  getStaticComponentFeed?: GeneralContentScreenProps["getStaticComponentFeed"];
  componentIndex?: number;
  isScreenWrappedInContainer?: boolean;
  isLast?: boolean;
};

export function zappPipesDataConnector(
  Component: React.FC<any> | React.ComponentClass<any>
) {
  return function WrappedWithZappPipesData(props: Props) {
    const { screenData } = useRoute();
    const { plugins } = usePickFromState(["plugins"]);
    const screenContextData = useScreenContext();

    const {
      component,
      feedUrl,
      getStaticComponentFeed,
      componentIndex,
      isScreenWrappedInContainer,
      riverId,
      isLast = false,
    } = props;

    // Handle context determination
    // HACK for the tabs screen which needs to use 2 types of context.
    const shouldUseNestedContext = isScreenWrappedInContainer && riverId;

    const entryContext =
      (shouldUseNestedContext && screenContextData?.nested?.entry
        ? screenContextData?.nested?.entry
        : (screenContextData?.entry?.payload ?? screenContextData?.entry)) ||
      {};

    const screenContext =
      (shouldUseNestedContext && screenContextData?.nested?.screen
        ? screenContextData?.nested?.screen
        : screenContextData?.screen) || {};

    const [searchContext] = ZappPipesSearchContext.useZappPipesContext();

    // Prepare context for resolvers
    const resolverProps: ComponentDataSourceContext = {
      component,
      feedUrl,
      getStaticComponentFeed,
      componentIndex,
      isScreenWrappedInContainer,
      riverId,
      isLast,
      entryContext,
      screenContext,
      searchContext,
      screenData,
      plugins,
    };

    return (
      <ResolverSelector {...resolverProps}>
        {(zappPipesDataProps) => (
          <Component {...props} {...zappPipesDataProps} />
        )}
      </ResolverSelector>
    );
  };
}
