import * as React from "react";
import { path, prop } from "ramda";
import {
  findPluginByType,
  findPluginByIdentifier,
} from "@applicaster/zapp-react-native-utils/pluginUtils";
import { HandlePlayable } from "../../HandlePlayable";
import { HookRenderer } from "../../HookRenderer";
import { LinkHandler } from "../../LinkHandler";
import { Favorites } from "../../Favorites";
import { usePlugins } from "@applicaster/zapp-react-native-redux/hooks";
import { useNavigation } from "@applicaster/zapp-react-native-utils/reactHooks";

import { useCallbackActions } from "@applicaster/zapp-react-native-utils/zappFrameworkUtils/HookCallback/useCallbackActions";
import { useGetComponent } from "./useGetComponent";
import { getScreenTypeProps } from "../utils";

export enum PresentationType {
  Standalone = "Standalone",
  Hook = "Hook",
}

const screenTypeComponents = {
  favorites: Favorites,
  link: LinkHandler,
  playable: HandlePlayable,
  hooks: HookRenderer,
};

export const useScreenComponentResolver = (screenType, props) => {
  const plugins = usePlugins();
  const { hookPlugin } = props.screenData || {};
  const component = useGetComponent(screenType);

  const screenAction = useCallbackActions(
    hookPlugin || props.screenData,
    props.screenData.callback
  );

  const {
    videoModalState: { mode },
  } = useNavigation();

  const componentProps = {
    ...props,
    mode,
    screenAction,
  };

  const ScreenTypeComponent = screenTypeComponents?.[screenType];

  if (ScreenTypeComponent) {
    return (
      <ScreenTypeComponent
        {...getScreenTypeProps(screenType, componentProps)}
      />
    );
  }

  const ScreenPlugin =
    findPluginByType(screenType, plugins, { skipWarning: true }) ||
    findPluginByIdentifier(screenType, plugins) ||
    findPluginByIdentifier(hookPlugin && hookPlugin.identifier, plugins) ||
    component;

  const ScreenComponent =
    path(["module", "Component"], ScreenPlugin) ||
    prop("module", ScreenPlugin) ||
    prop("Component", ScreenPlugin) ||
    ScreenPlugin;

  const configuration =
    prop("configuration", ScreenPlugin) ||
    prop("__plugin_configuration", ScreenComponent);

  if (!ScreenComponent) {
    return null;
  }

  return (
    <ScreenComponent
      {...props}
      callback={props.resultCallback || screenAction}
      screenId={props.screenId}
      screenData={props.screenData}
      presentationType={PresentationType.Standalone}
      configuration={configuration}
    />
  );
};
