import React, { useEffect } from 'react';
import { StatusBar, ActivityIndicator, View, StyleSheet } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { colors } from '../theme/colors';
import { useAuthStore } from '../stores/auth.store';
import { useThemeStore } from '../stores/theme.store';
import { AppNavigation } from './navigation';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 2,
      staleTime: 5 * 60 * 1000,
      gcTime: 10 * 60 * 1000,
    },
    mutations: {
      retry: 0,
    },
  },
});

function AppContent(): React.JSX.Element {
  const styles = createStyles();
  const { isLoading, restoreSession } = useAuthStore();

  useEffect(() => {
    void restoreSession();
  }, [restoreSession]);

  if (isLoading) {
    return (
      <View style={[styles.loading, { backgroundColor: colors.background }]}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  return <AppNavigation />;
}

function ThemeGate({ children }: { children: React.ReactNode }): React.JSX.Element {
  const themeId = useThemeStore((s) => s.themeId);
  const isDark = useThemeStore((s) => s.isDark);
  const restoreTheme = useThemeStore((s) => s.restoreTheme);
  const startPolling = useThemeStore((s) => s.startPolling);

  useEffect(() => {
    void restoreTheme();
    const stopPolling = startPolling();
    return stopPolling;
  }, [restoreTheme, startPolling]);

  return (
    <React.Fragment key={themeId}>
      <StatusBar
        barStyle={isDark ? 'light-content' : 'dark-content'}
        backgroundColor={colors.card}
      />
      {children}
    </React.Fragment>
  );
}

export default function App(): React.JSX.Element {
  return (
    <SafeAreaProvider>
      <QueryClientProvider client={queryClient}>
        <ThemeGate>
          <AppContent />
        </ThemeGate>
      </QueryClientProvider>
    </SafeAreaProvider>
  );
}

const createStyles = () =>
  StyleSheet.create({
    loading: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
  });
