import React, { ReactNode, useEffect } from 'react';
import { useSession } from 'hooks/session';
import { usePushNotification } from 'hooks/push-notification';
import { useAppState, useInternetState, useResponsiveLayout } from 'hooks';
import { offlineQueueLink } from 'expo-schema/client/client';
import { isLoggedInVar } from 'state-management/session';
import { useReactiveVar } from '@apollo/client';

export const SessionContext = React.createContext<SessionContextType>({
  loadingSession: true,
  checkSession: () => {},
});

export const SessionProvider: React.FC<SessionProps> = ({ children }) => {
  const { loadingSession, checkSession } = useSession();
  const isLoggedIn = useReactiveVar(isLoggedInVar);
  const { isHandHeld } = useResponsiveLayout();
  const { appState } = useAppState();

  const { registerForPushNotificationsAsync } = usePushNotification();
  const { isConnected } = useInternetState();

  useEffect(() => {
    if (isHandHeld) {
      checkSession();
    }
  }, [checkSession, appState, isHandHeld]);

  useEffect(() => {
    if (!isHandHeld) {
      document.addEventListener('visibilitychange', checkSession);
    }
    return () => {
      if (!isHandHeld) {
        document.removeEventListener('visibilitychange', checkSession);
      }
    };
  }, [checkSession, isHandHeld]);

  useEffect(() => {
    if (isConnected) {
      offlineQueueLink.open();
    } else {
      offlineQueueLink.close();
    }
  }, [isConnected, isLoggedIn, registerForPushNotificationsAsync]);

  useEffect(() => {
    if (isLoggedIn) {
      registerForPushNotificationsAsync();
    }
  }, [isLoggedIn, registerForPushNotificationsAsync]);

  return (
    <SessionContext.Provider value={{ loadingSession, checkSession }}>
      {children}
    </SessionContext.Provider>
  );
};

export interface SessionContextType {
  loadingSession: boolean;
  checkSession: () => void;
}

interface SessionProps {
  children?: ReactNode;
}
