import * as React from "react";
import { isTV } from "@applicaster/zapp-react-native-utils/reactUtils";
import {
  useBackHandler,
  useIsNavBarVisible,
} from "@applicaster/zapp-react-native-utils/reactHooks/navigation";
import { useHookAnalytics } from "@applicaster/zapp-react-native-utils/analyticsUtils/helpers/hooks";
import { useSetNavbarState } from "@applicaster/zapp-react-native-utils/reactHooks";

type Props = {
  focused?: boolean;
  parentFocus?: ParentFocus;
  screenData: HookPluginProps;
};

export const HookRenderer = (props: Props) => {
  const {
    focused,
    screenData: { callback, payload, hookPlugin },
  } = props;

  const { setVisible: showNavBar } = useSetNavbarState();

  const {
    module: { Component: HookComponent, presentFullScreen },
    configuration,
  } = hookPlugin;

  useHookAnalytics(props);

  const isNavBarVisible = useIsNavBarVisible();

  useBackHandler(() => {
    callback({ success: false, payload, cancelled: true });

    return true;
  });

  React.useEffect(() => {
    if (presentFullScreen && isTV()) {
      showNavBar(false);
    }

    return () => {
      if (isTV()) {
        showNavBar(true);
      }
    };
  }, [showNavBar]);

  // Passing empty parentFocus if navbar is not visible (fullScreen hook)
  const parentFocus = isNavBarVisible ? props.parentFocus : {};

  return (
    <HookComponent
      {...{
        callback,
        payload,
        configuration,
        hookPlugin,
        focused,
        parentFocus,
      }}
    />
  );
};
