import React from "react";
import { useActions } from "@applicaster/zapp-react-native-utils/reactHooks/actions";
import { useAppState } from "@applicaster/zapp-react-native-utils/reactHooks/app";
import { isApplePlatform } from "@applicaster/zapp-react-native-utils/reactUtils";

const CHROMECAST_IDENTIFIER = "quick-brick-chromecast-action";

const fakeEntry: any = {
  title: "Chromecast use is casting fake entry",
  id: "quick-brick-use-is-casting-fake-entry",
};

/**
 * Returns the cast action state connection status, does not update when app is in background on Apple platforms
 * On other platforms, it continues to check the cast action state even when the app is in background
 */
export const useIsCasting = () => {
  const actionContext = useActions(CHROMECAST_IDENTIFIER);
  const appState = useAppState();
  const isAppInForeground = appState === "active";
  const shouldOnlyUpdateInForeground = isApplePlatform();

  const [castActionState, setCastActionState] = React.useState(
    !actionContext ? null : actionContext.initialEntryState(fakeEntry)
  );

  React.useEffect(() => {
    if (!shouldOnlyUpdateInForeground || isAppInForeground) {
      if (actionContext && castActionState === null) {
        setCastActionState(actionContext.initialEntryState(fakeEntry));
      }
    }
  }, [
    actionContext,
    setCastActionState,
    isAppInForeground,
    shouldOnlyUpdateInForeground,
  ]);

  React.useEffect(() => {
    if (typeof actionContext?.addListener === "function") {
      return actionContext?.addListener(String(fakeEntry.id), (state) => {
        // Only check foreground state on Apple platforms
        if (!shouldOnlyUpdateInForeground || isAppInForeground) {
          setCastActionState(state);
        }
      });
    }
  }, [
    setCastActionState,
    actionContext,
    isAppInForeground,
    shouldOnlyUpdateInForeground,
  ]);

  return !!castActionState?.connected;
};
