import { MONITOR_ENABLED } from '@/remote/monitor';
import {
  StatsigProviderExpo,
  useStatsigClient as useStatsigClientInternal,
} from '@statsig/expo-bindings';
import { ReactNode, useEffect, useMemo, useRef } from 'react';

export type MonitorUser = {
  id: string;
  isAnonymous: boolean;
};

export type MonitorEvent = 'app_opened';

const SDK_KEY = process.env.EXPO_PUBLIC_STATSIG_CLIENT_KEY ?? '';

function UserUpdater({ user }: { user: MonitorUser }) {
  const { client } = useStatsigClientInternal();
  const prev = useRef({ id: user.id, isAnonymous: user.isAnonymous });

  useEffect(() => {
    if (prev.current.id !== user.id || prev.current.isAnonymous !== user.isAnonymous) {
      prev.current = { id: user.id, isAnonymous: user.isAnonymous };
      client
        .updateUserAsync({ userID: user.id, custom: { isAnonymous: user.isAnonymous } })
        .catch(console.warn);
    }
  }, [client, user.id, user.isAnonymous]);

  return null;
}

function AppOpenedLogger() {
  const { client } = useStatsigClientInternal();
  const logged = useRef(false);

  useEffect(() => {
    if (!logged.current) {
      logged.current = true;
      client.logEvent('app_opened');
    }
  }, [client]);

  return null;
}

export function StatsigProvider({ user, children }: { user: MonitorUser; children: ReactNode }) {
  const statsigUser = useMemo(
    () => ({
      userID: user.id,
      custom: { isAnonymous: user.isAnonymous },
    }),
    [user.id, user.isAnonymous]
  );

  if (!MONITOR_ENABLED || !SDK_KEY) {
    return <>{children}</>;
  }

  return (
    <StatsigProviderExpo sdkKey={SDK_KEY} user={statsigUser}>
      <UserUpdater user={user} />
      <AppOpenedLogger />
      {children}
    </StatsigProviderExpo>
  );
}

export function useStatsigClient() {
  return useStatsigClientInternal();
}
