import '#/logger/sentry/setup'

import {Fragment, useEffect, useState} from 'react'
import {GestureHandlerRootView} from 'react-native-gesture-handler'
import {KeyboardProvider as KeyboardControllerProvider} from 'react-native-keyboard-controller'
import {
  initialWindowMetrics,
  SafeAreaProvider,
} from 'react-native-safe-area-context'
import * as ScreenOrientation from 'expo-screen-orientation'
import * as SplashScreen from 'expo-splash-screen'
import * as SystemUI from 'expo-system-ui'
import {useLingui} from '@lingui/react/macro'
import * as Sentry from '@sentry/react-native'

import {Provider as HideBottomBarBorderProvider} from '#/lib/hooks/useHideBottomBarBorder'
import {QueryProvider} from '#/lib/react-query'
import {ThemeProvider} from '#/lib/ThemeContext'
import {Provider as TranslateOnDeviceProvider} from '#/lib/translation'
import I18nProvider from '#/locale/i18nProvider'
import {logger} from '#/logger'
import {Provider as A11yProvider} from '#/state/a11y'
import {
  prefetchAppConfig,
  Provider as AppConfigProvider,
} from '#/state/appConfig'
import {Provider as MutedThreadsProvider} from '#/state/cache/thread-mutes'
import {Provider as DialogStateProvider} from '#/state/dialogs'
import {Provider as EmailVerificationProvider} from '#/state/email-verification'
import {listenSessionDropped} from '#/state/events'
import {GlobalGestureEventsProvider} from '#/state/global-gesture-events'
import {Provider as HomeBadgeProvider} from '#/state/home-badge'
import {MessagesProvider} from '#/state/messages'
import {Provider as ModalStateProvider} from '#/state/modals'
import {init as initPersistedState} from '#/state/persisted'
import {Provider as PrefsStateProvider} from '#/state/preferences'
import {Provider as LabelDefsProvider} from '#/state/preferences/label-defs'
import {Provider as ModerationOptsProvider} from '#/state/preferences/moderation-opts'
import {Provider as UnreadNotifsProvider} from '#/state/queries/notifications/unread'
import {Provider as ServiceAccountManager} from '#/state/service-config'
import {
  Provider as SessionProvider,
  type SessionAccount,
  useSession,
  useSessionApi,
} from '#/state/session'
import {readLastActiveAccount} from '#/state/session/util'
import {Provider as ShellStateProvider} from '#/state/shell'
import {Provider as ComposerProvider} from '#/state/shell/composer'
import {Provider as LandingProvider} from '#/state/shell/landing'
import {Provider as LoggedOutViewProvider} from '#/state/shell/logged-out'
import {Provider as OnboardingProvider} from '#/state/shell/onboarding'
import {Provider as ProgressGuideProvider} from '#/state/shell/progress-guide'
import {Provider as SelectedFeedProvider} from '#/state/shell/selected-feed'
import {Provider as HiddenRepliesProvider} from '#/state/threadgate-hidden-replies'
import {TestCtrls} from '#/view/com/testing/TestCtrls'
import {Shell} from '#/view/shell'
import {atoms as a, ThemeProvider as Alf} from '#/alf'
import {useColorModeTheme} from '#/alf/util/useColorModeTheme'
import {Provider as ContextMenuProvider} from '#/components/ContextMenu'
import {useLandingEntry} from '#/components/hooks/useLandingEntry'
import {Provider as IntentDialogProvider} from '#/components/intents/IntentDialogs'
import {Provider as LightboxStateProvider} from '#/components/Lightbox/state'
import {Provider as PolicyUpdateOverlayProvider} from '#/components/PolicyUpdateOverlay'
import {Provider as PortalProvider} from '#/components/Portal'
import {Provider as VideoVolumeProvider} from '#/components/Post/Embed/VideoEmbed/VideoVolumeContext'
import * as Toast from '#/components/Toast'
import {ToastOutlet} from '#/components/Toast'
import {
  prefetchAgeAssuranceConfig,
  Provider as AgeAssuranceV2Provider,
} from '#/ageAssurance'
import {
  AnalyticsContext,
  AnalyticsFeaturesContext,
  features,
  setupDeviceId,
} from '#/analytics'
import {IS_ANDROID, IS_IOS} from '#/env'
import {
  prefetchLiveEvents,
  Provider as LiveEventsProvider,
} from '#/features/liveEvents/context'
import {SettingsSyncGate} from '#/features/settingsSync'
import * as Geo from '#/geolocation'
import {Splash} from '#/Splash'
import {BottomSheetProvider} from '../modules/bottom-sheet'
import {BackgroundNotificationPreferencesProvider} from '../modules/expo-background-notification-handler/src/BackgroundNotificationHandlerProvider'

void SplashScreen.preventAutoHideAsync()
if (IS_IOS) {
  void SystemUI.setBackgroundColorAsync('black')
}
if (IS_ANDROID) {
  // iOS is handled by the config plugin -sfn
  ScreenOrientation.lockAsync(
    ScreenOrientation.OrientationLock.PORTRAIT_UP,
  ).catch(error =>
    logger.debug('Could not lock orientation', {safeMessage: error}),
  )
}

/**
 * Begin geolocation ASAP
 */
void Geo.resolve()
void prefetchAgeAssuranceConfig()
void prefetchLiveEvents()
void prefetchAppConfig()

function InnerApp() {
  const [isReady, setIsReady] = useState(false)
  const {currentAccount} = useSession()
  const {resumeSession} = useSessionApi()
  const theme = useColorModeTheme()
  const {t: l} = useLingui()
  const hasCheckedLanding = useLandingEntry()

  // init
  useEffect(() => {
    async function onLaunch(account?: SessionAccount) {
      try {
        if (account) {
          await resumeSession(account)
        } else {
          await features.init
        }
      } catch (e) {
        logger.error(`session: resume failed`, {message: e})
      } finally {
        setIsReady(true)
      }
    }
    const account = readLastActiveAccount()
    void onLaunch(account)
  }, [resumeSession])

  useEffect(() => {
    return listenSessionDropped(() => {
      Toast.show(l`Sorry! Your session expired. Please sign in again.`, {
        type: 'info',
      })
    })
  }, [l])

  return (
    <Alf theme={theme}>
      <ThemeProvider theme={theme}>
        <ContextMenuProvider>
          <Splash isReady={isReady && hasCheckedLanding}>
            <VideoVolumeProvider>
              <Fragment
                // Resets the entire tree below when it changes:
                key={currentAccount?.did}>
                <AnalyticsFeaturesContext>
                  <QueryProvider currentDid={currentAccount?.did}>
                    <SettingsSyncGate>
                    <PolicyUpdateOverlayProvider>
                      <LiveEventsProvider>
                        <AgeAssuranceV2Provider>
                          <ComposerProvider>
                            <MessagesProvider>
                              {/* LabelDefsProvider MUST come before ModerationOptsProvider */}
                              <LabelDefsProvider>
                                <ModerationOptsProvider>
                                  <LoggedOutViewProvider>
                                    <SelectedFeedProvider>
                                      <HiddenRepliesProvider>
                                        <HomeBadgeProvider>
                                          <UnreadNotifsProvider>
                                            <BackgroundNotificationPreferencesProvider>
                                              <MutedThreadsProvider>
                                                <ProgressGuideProvider>
                                                  <ServiceAccountManager>
                                                    <EmailVerificationProvider>
                                                      <HideBottomBarBorderProvider>
                                                        <GestureHandlerRootView
                                                          style={a.h_full}>
                                                          <GlobalGestureEventsProvider>
                                                            <IntentDialogProvider>
                                                              <TranslateOnDeviceProvider>
                                                                <TestCtrls />
                                                                <Shell />
                                                                <ToastOutlet />
                                                              </TranslateOnDeviceProvider>
                                                            </IntentDialogProvider>
                                                          </GlobalGestureEventsProvider>
                                                        </GestureHandlerRootView>
                                                      </HideBottomBarBorderProvider>
                                                    </EmailVerificationProvider>
                                                  </ServiceAccountManager>
                                                </ProgressGuideProvider>
                                              </MutedThreadsProvider>
                                            </BackgroundNotificationPreferencesProvider>
                                          </UnreadNotifsProvider>
                                        </HomeBadgeProvider>
                                      </HiddenRepliesProvider>
                                    </SelectedFeedProvider>
                                  </LoggedOutViewProvider>
                                </ModerationOptsProvider>
                              </LabelDefsProvider>
                            </MessagesProvider>
                          </ComposerProvider>
                        </AgeAssuranceV2Provider>
                      </LiveEventsProvider>
                    </PolicyUpdateOverlayProvider>
                    </SettingsSyncGate>
                  </QueryProvider>
                </AnalyticsFeaturesContext>
              </Fragment>
            </VideoVolumeProvider>
          </Splash>
        </ContextMenuProvider>
      </ThemeProvider>
    </Alf>
  )
}

function App() {
  const [isReady, setIsReady] = useState(false)

  useEffect(() => {
    void Promise.all([initPersistedState(), Geo.resolve(), setupDeviceId]).then(
      () => setIsReady(true),
    )
  }, [])

  if (!isReady) {
    return null
  }

  /*
   * NOTE: only nothing here can depend on other data or session state, since
   * that is set up in the InnerApp component above.
   */
  return (
    <Geo.Provider>
      <AppConfigProvider>
        <A11yProvider>
          <KeyboardControllerProvider preload={false}>
            <OnboardingProvider>
              <AnalyticsContext>
                <SessionProvider>
                  <PrefsStateProvider>
                    <I18nProvider>
                      <ShellStateProvider>
                        <ModalStateProvider>
                          <DialogStateProvider>
                            <LightboxStateProvider>
                              <PortalProvider>
                                <BottomSheetProvider>
                                  <LandingProvider>
                                    <SafeAreaProvider
                                      initialMetrics={initialWindowMetrics}>
                                      <InnerApp />
                                    </SafeAreaProvider>
                                  </LandingProvider>
                                </BottomSheetProvider>
                              </PortalProvider>
                            </LightboxStateProvider>
                          </DialogStateProvider>
                        </ModalStateProvider>
                      </ShellStateProvider>
                    </I18nProvider>
                  </PrefsStateProvider>
                </SessionProvider>
              </AnalyticsContext>
            </OnboardingProvider>
          </KeyboardControllerProvider>
        </A11yProvider>
      </AppConfigProvider>
    </Geo.Provider>
  )
}

export default Sentry.wrap(App)
