import {
  NavigationContainer /*, DefaultTheme*/,
} from '@react-navigation/native';
import React, { useRef, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import {
  navigationBetweenScreens$,
  noNavigationParamsChange$,
  setTopLevelNavigator,
} from '../../common/utils/navigation-service';
import { theme } from '../theme';
import { AppSwitch } from './app-switch';
import { ENV } from '../../../env';
import { PERSISTENCE_KEY, resetNavigationPeristence } from './dev-tools';
import {
  SENTRY_BREADCRUMB,
  useSentryRenderRecursionDetector,
} from '../../common/utils/debuggers/sentry-logger';
import { fp as _ } from '../../common/utils/fp';

// @ts-ignore
if (global.__DEV__ && ENV.features.devResetNavigation) {
  resetNavigationPeristence();
}

export const Navigator: React.FC = () => {
  const navigationRef = React.useRef(null);
  const routeNameRef = useRef();
  useEffect(() => {
    setTopLevelNavigator(navigationRef.current);
  }, [navigationRef.current]);

  const [isReady, setIsReady] = React.useState(
    // @ts-ignore
    !global.__DEV__ || ENV.features.devResetNavigation
  );
  const [initialState, setInitialState] = React.useState();

  useSentryRenderRecursionDetector('navigation');

  useEffect(() => {
    const restoreState = async () => {
      try {
        // const initialUrl = await Linking.getInitialURL();

        // if (Platform.OS !== 'web' && initialUrl == null) {
        // Only restore state if there's no deep link and we're not on web
        const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
        const state = savedStateString
          ? JSON.parse(savedStateString)
          : undefined;

        if (state !== undefined) {
          setInitialState(state);
        }
        // }
      } finally {
        setIsReady(true);
      }
    };
    if (!isReady) {
      restoreState();
    }
  }, [isReady]);

  if (!isReady) {
    return null;
  }

  return (
    <SafeAreaProvider>
      <NavigationContainer
        theme={{
          // https://reactnavigation.org/docs/themes/
          // @ts-ignore
          colors: {
            background: theme.colors.ebonyClay,
          },
        }}
        ref={navigationRef}
        onReady={() => {
          setTopLevelNavigator(navigationRef.current);
          // @ts-ignore
          routeNameRef.current = navigationRef.current.getCurrentRoute();
        }}
        initialState={initialState}
        onStateChange={async state => {
          // @ts-ignore
          if (global.__DEV__ && !ENV.features.devResetNavigation) {
            AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state));
          }

          const previousRoute = routeNameRef.current;
          // @ts-ignore
          const currentRoute = navigationRef.current.getCurrentRoute();

          // Save the current route name for later comparison
          routeNameRef.current = currentRoute;

          // const prev = getCurrentRoute(prevState);
          // const next = getCurrentRoute(currentState);

          const prev = {
            // @ts-ignore
            ...previousRoute,
            // @ts-ignore
            routeName: previousRoute.name,
          };
          const next = {
            ...currentRoute,
            routeName: currentRoute.name,
          };

          if (prev && next && prev.routeName !== next.routeName) {
            SENTRY_BREADCRUMB.navigationRouteChange(prev, next);

            navigationBetweenScreens$.next({
              prev,
              next,
            });
          } else if (!_.isEqual(next.params, prev.params)) {
            SENTRY_BREADCRUMB.navigationRouteParamChange(prev, next);

            noNavigationParamsChange$.next({
              prev,
              next,
            });
          }
        }}
      >
        <AppSwitch />
      </NavigationContainer>
    </SafeAreaProvider>
  );
};
