import { useNavigation } from '@react-navigation/native';
import * as SplashScreen from 'expo-splash-screen';
import React, {
  createContext,
  Dispatch,
  FC,
  ReactElement,
  SetStateAction,
  useContext,
  useEffect,
  useLayoutEffect,
  useState,
} from 'react';

import { NavProps } from '../components/Routes/Routes';
import { useAppLoading } from './useAppLoading';
import { useUserInfo } from './useStorage';

type SplashScreenState = [boolean, Dispatch<SetStateAction<boolean>>];

const SplashScreenContext = createContext<SplashScreenState>(undefined as never);

type props = {
  children: ReactElement;
};

export const SplashScreenProvider: FC<props> = ({ children }) => {
  const [showSplashScreen, setShowSplashScreen] = useState<boolean>(true);
  useEffect(() => {
    const prepare = async () => {
      await SplashScreen.preventAutoHideAsync();
    };
    prepare();
  }, []);

  useLayoutEffect(() => {
    const close = async () => {
      if (!showSplashScreen) {
        await SplashScreen.hideAsync();
      }
    };
    close();
  }, [showSplashScreen]);

  return (
    <SplashScreenContext.Provider value={[showSplashScreen, setShowSplashScreen]}>
      {children}
    </SplashScreenContext.Provider>
  );
};

export const useSplashScreen = () => {
  const [, setShowSplashScreen] = useContext(SplashScreenContext);
  const hideSplashScreen = () => setShowSplashScreen(false);
  return hideSplashScreen;
};

export const useLoggedUserSplashScreen = () => {
  const navigation = useNavigation<NavProps>();
  const [isAppLoading] = useAppLoading();
  const [userInfo] = useUserInfo();

  const hideSplashScreen = useSplashScreen();

  useEffect(() => {
    if (!userInfo.token) {
      navigation.replace('Landing');
    }
    if (!isAppLoading) {
      hideSplashScreen();
    }
  }, [hideSplashScreen, isAppLoading, userInfo]);
  return isAppLoading;
};
