import * as React from "react";
import { focusManager } from "@applicaster/zapp-react-native-utils/appUtils";

import { useSubscriberFor } from "@applicaster/zapp-react-native-utils/reactHooks/useSubscriberFor";
import { QBUIComponentEvents } from "@applicaster/zapp-react-native-ui-components/events";

import {
  useCurrentScreenIsHome,
  useCurrentScreenIsRoot,
  useCurrentScreenIsTabs,
} from "./hooks";

import {
  useCurrentScreenIsHook,
  useCurrentScreenIsStartupHook,
  useIsStandaloneFullscreen,
} from "@applicaster/zapp-react-native-utils/reactHooks/screen";

export function withBackToTopActionHOC(Component) {
  return function WrappedComponent(props) {
    const isHome = useCurrentScreenIsHome();
    const isRoot = useCurrentScreenIsRoot();
    const isTabsScreen = useCurrentScreenIsTabs();

    const isStartUpHook = useCurrentScreenIsStartupHook();

    const isHook = useCurrentScreenIsHook();

    const isStandaloneFullscreen = useIsStandaloneFullscreen();

    const emitFocusOnSelectedTab = useSubscriberFor(
      QBUIComponentEvents.focusOnSelectedTab
    );

    const emitFocusOnSelectedTopMenuItem = useSubscriberFor(
      QBUIComponentEvents.focusOnSelectedTopMenuItem
    );

    const backToTopAction = React.useCallback((): BackToTopAction => {
      if (isStartUpHook) {
        return "PLATFORM_BACK";
      }

      if (isHook) {
        return "GO_BACK_FROM_HOOK";
      }

      // Handling case where is not top menu visible
      if (isStandaloneFullscreen) {
        return "GO_HOME";
      }

      if (isRoot && focusManager.isFocusOnMenu() && isHome) {
        return "PLATFORM_BACK";
      }

      if (isRoot && focusManager.isFocusOnMenu() && !isHome) {
        return "GO_HOME";
      }

      if (isRoot && isTabsScreen && focusManager.isTabsScreenContentFocused()) {
        return "FOCUS_ON_SELECTED_TAB_ITEM";
      }

      if (isRoot && focusManager.isFocusOnContent()) {
        return "FOCUS_ON_SELECTED_TOP_MENU_ITEM";
      }

      // default
      return "GO_BACK";
    }, [
      isHome,
      isRoot,
      isTabsScreen,
      isStartUpHook,
      isHook,
      isStandaloneFullscreen,
    ]);

    return (
      <Component
        {...props}
        backToTopAction={backToTopAction}
        emitFocusOnSelectedTab={emitFocusOnSelectedTab}
        emitFocusOnSelectedTopMenuItem={emitFocusOnSelectedTopMenuItem}
      />
    );
  };
}
