import React, { useEffect, useMemo } from 'react';
import { Platform, StatusBar, View } from "react-native";
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { ThemedView } from './components/themed-view';
import { ThemedText } from './components/themed-text';
import { ApiProvider } from './lib/network/api';
import { Themes } from './lib/theme';
import { useColorScheme } from './lib/hooks/use-color-scheme';
import { WebSocketProvider } from './lib/network/ws';
import { useBaseStore } from './lib/stores/base';
import { useWsStore } from './lib/stores/ws';
import SystemNavigationBar from 'react-native-system-navigation-bar';
import { useThemeColor } from './lib/hooks/use-theme-color';
import Conversation from './screens/conversation';
import { useChatStore } from './lib/stores/chats';
import { ActionSheetProvider } from '@expo/react-native-action-sheet';
import Login from './screens/login';
import Main from './screens/main';
import { getChannelName } from './lib/types/discord';

export type RootStackParamList = {
  Login: undefined;
  Main: undefined;
  Conversation: { id: string };
};

const Stack = createStackNavigator<RootStackParamList>();

export default function RootLayout() {
  const colorScheme = useColorScheme();
  const isDark = useMemo(() => colorScheme === 'dark', [colorScheme]);
  const bgColor = useThemeColor('card');

  useEffect(() => {
    if (Platform.OS === 'android' && Number(Platform.Version) >= 23) {
      SystemNavigationBar.setNavigationColor(bgColor, isDark);
      StatusBar.setBarStyle(isDark ? 'light-content' : 'dark-content');
      StatusBar.setBackgroundColor('transparent');
      StatusBar.setTranslucent(true);
    }
  }, [bgColor, isDark]);

  return (
    <ActionSheetProvider>
      <ApiProvider>
        <WebSocketProvider>
          <SafeAreaProvider>
            <NavigationContainer theme={isDark ? Themes.dark : Themes.light}>
              <ThemedView style={{ flex: 1 }}>
                <RootNavigator />
              </ThemedView>
            </NavigationContainer>
          </SafeAreaProvider>
        </WebSocketProvider>
      </ApiProvider>
    </ActionSheetProvider>
  );
}

function LoadingScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <ThemedText type="subtitle">Loading…</ThemedText>
    </View>
  );
}

function RootNavigator() {
  const user = useBaseStore((s) => s.user);
  const token = useBaseStore((s) => s.token);
  const connected = useWsStore((s) => s.connected);
  const privateChannels = useChatStore((s) => s.privateChannels);

  if (token && (!user || !connected))
    return <LoadingScreen />;

  return (
    <Stack.Navigator screenOptions={{ headerShown: false }}>
      {!user || !token ? (
        <Stack.Screen name="Login" component={Login} />
      ) : (
        <>
          <Stack.Screen name="Main" component={Main} />
          <Stack.Screen
            name="Conversation"
            component={Conversation}
            options={({ route }) => {
              const channel = privateChannels[route.params.id];
              return { headerShown: true, title: getChannelName(channel) };
            }}
          />
        </>
      )}
    </Stack.Navigator>
  );
}