import * as React from "react";
import { path, max } from "ramda";
import { isTrue } from "@applicaster/zapp-react-native-utils/booleanUtils";
import { toNumberWithDefault } from "@applicaster/zapp-react-native-utils/numberUtils";
import { useIsScreenActive } from "@applicaster/zapp-react-native-utils/reactHooks/navigation";

import { reactHooksLogger } from "../logger";
import { ReloadDataFunction } from "./useFeedLoader";

export const feedRefreshLogger = reactHooksLogger.addSubsystem("feed-refresh");

type Props = {
  reloadData?: ReloadDataFunction;
  component: ZappUIComponent;
};

const previousTimersMap = {};
const minimumRefreshingInterval = 5;
const defaultRefreshInterval = 60;

export const useFeedRefresh = ({ reloadData, component }: Props): void => {
  const isDataRefreshingEnabled = isTrue(
    path(["rules", "enable_data_refreshing"], component)
  );

  const refreshing_interval = toNumberWithDefault(
    defaultRefreshInterval,
    component?.rules?.refreshing_interval
  );

  const refreshingIntervalInMilliseconds =
    max(refreshing_interval, minimumRefreshingInterval) * 1000;

  const isScreenActive = useIsScreenActive();

  React.useEffect(() => {
    if (isDataRefreshingEnabled && refreshing_interval && isScreenActive) {
      if (refreshing_interval < minimumRefreshingInterval) {
        feedRefreshLogger.warning({
          message: `You set your feed refresh interval to ${refreshing_interval} when minimum value is ${minimumRefreshingInterval}seconds.Your feed will refresh after ${minimumRefreshingInterval}seconds.`,
        });
      }

      if (!reloadData || typeof reloadData !== "function") {
        feedRefreshLogger.warning({
          message:
            "reloadData function is undefined, feed refresh feature won't work properly",
        });
      }

      if (previousTimersMap[component?.id]) {
        reloadData?.();
      }

      const refreshInterval = setInterval(() => {
        reloadData?.();
      }, refreshingIntervalInMilliseconds);

      return () => {
        previousTimersMap[component?.id] = true;
        clearInterval(refreshInterval);
      };
    }
  }, [reloadData, isScreenActive]);
};
