import { createDrawerNavigator } from '@react-navigation/drawer';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { useFonts } from 'expo-font';
import { StatusBar } from 'expo-status-bar';
import 'react-native-reanimated';
import { IconButton, PaperProvider } from 'react-native-paper';
import * as NavigationBar from 'expo-navigation-bar';

import { Platform, useColorScheme } from 'react-native';
import { lightTheme, darkTheme } from '@/constants/Colors';
import SettingsScreen from './SettingsScreen';
import { IconSymbol } from '@/components/ui/IconSymbol';
import { TouchableOpacity, View } from 'react-native';
import NullComponent from '@/components/NullComponent';
import { useEffect } from 'react';
import NewEntryScreen from './NewEntry';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';

// Import your tab screens directly
import HomeScreen from './HomeScreen';
import CalendarScreen from './(tabs)/calendar';
import MediaScreen from './(tabs)/media';
import AtlasScreen from './(tabs)/atlas';
import TodayScreen from './(tabs)/today';
import { ThemedView } from '@/components/ThemedView';
import { useNavigation } from 'expo-router';
import { ThemedText } from '@/components/ThemedText';
import Wrapper from '@/components/ui/Wrapper';

const Drawer = createDrawerNavigator();
const RootStack = createNativeStackNavigator();
const Tab = createBottomTabNavigator();

function TabsNavigator() {
  const colorScheme = useColorScheme();
  const theme = colorScheme === 'dark' ? darkTheme : lightTheme;
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();

  return (
    <Wrapper>
      <SafeAreaView
        edges={['top', 'left', 'right']}
        style={{
          flex: 1,
        }}>
        <View style={{
          backgroundColor: theme.colors.onPrimary,
          position: 'absolute',
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          top: insets.top + 20,
          left: 20,
          right: 20,
          borderRadius: 12,
          zIndex: 1000,
        }}>
          <IconButton icon="menu" size={24} onPress={() => {
            navigation.dispatch({ type: 'OPEN_DRAWER' });
          }} />
          <ThemedText
            style={{ fontSize: 15, color: theme.colors.primary, letterSpacing: 2, fontWeight: 'bold' }}
          >JOURNEY</ThemedText>
          <IconButton icon="magnify" size={24} onPress={() => {
            console.log('Search pressed');
          }} />
        </View><Tab.Navigator
          screenOptions={{
            tabBarActiveTintColor: theme.colors.primary,
            headerShown: false,
            tabBarStyle: Platform.select({
              ios: {
                position: 'absolute',
              },
              default: {},
            }),
          }}
        >
          <Tab.Screen
            name="Journey"
            component={HomeScreen}
            options={{
              tabBarIcon: ({ color, size }) => (
                <IconSymbol name="book" size={size} color={color} />
              ),
            }}
          />
          <Tab.Screen
            name="Calendar"
            component={CalendarScreen}
            options={{
              tabBarIcon: ({ color, size }) => (
                <IconSymbol name="calendar" size={size} color={color} />
              ),
            }}
          />
          <Tab.Screen
            name="Media"
            component={MediaScreen}
            options={{
              tabBarIcon: ({ color, size }) => (
                <IconSymbol name="photo" size={size} color={color} />
              ),
            }}
          />
          <Tab.Screen
            name="Atlas"
            component={AtlasScreen}
            options={{
              tabBarIcon: ({ color, size }) => (
                <IconSymbol name="map" size={size} color={color} />
              ),
            }}
          />
          <Tab.Screen
            name="Today"
            component={TodayScreen}
            options={{
              tabBarIcon: ({ color, size }) => (
                <IconSymbol name="today" size={size} color={color} />
              ),
            }}
          />
        </Tab.Navigator>
      </SafeAreaView>
    </Wrapper>
  );
}

function DrawerNavigator() {
  const colorScheme = useColorScheme();
  const theme = colorScheme === 'dark' ? darkTheme : lightTheme;

  return (
    <Drawer.Navigator>
      <Drawer.Screen
        name="Tabs"
        component={TabsNavigator}
        options={{
          headerShown: false,
          drawerItemStyle: { display: 'none' }
        }}
      />
      <Drawer.Group
        screenOptions={{
          headerShown: false,
          drawerActiveTintColor: theme.colors.primary,
          drawerInactiveTintColor: theme.colors.onSurfaceVariant,
          drawerStyle: {
            backgroundColor: theme.colors.background,
          },
        }}
      >
        <Drawer.Screen
          name="SettingsDrawerItem"
          component={NullComponent}
          options={{
            title: 'Settings',
            headerShown: false,
            drawerLabel: 'Settings',
            drawerIcon: ({ color }) => (
              <IconSymbol name="settings" size={24} color={color} />
            ),
          }}
          listeners={({ navigation }) => ({
            drawerItemPress: (e) => {
              e.preventDefault();
              navigation.getParent()?.navigate('Settings');
              navigation.dispatch({ type: 'CLOSE_DRAWER' });
            },
          })}
        />
      </Drawer.Group>
    </Drawer.Navigator>
  );
}

export default function RootLayout() {
  const [loaded] = useFonts({
    SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
  });
  const colorScheme = useColorScheme();
  const theme = colorScheme === 'dark' ? darkTheme : lightTheme;

  useEffect(() => {
    if (Platform.OS === 'android') {
      NavigationBar.setStyle('inverted');
    }
  }, [colorScheme]);

  if (!loaded) {
    return null;
  }

  return (
    <PaperProvider theme={theme}>

      <RootStack.Navigator>
        <RootStack.Screen
          name="Main"
          component={DrawerNavigator}
          options={{ headerShown: false }}
        />
        <RootStack.Screen
          name="Settings"
          component={SettingsScreen}
          options={({ navigation }) => ({
            headerBackVisible: false,
            gestureEnabled: false,
            headerTitle: 'Settings',
            headerLeft: () => (
              <TouchableOpacity
                onPress={() => {
                  navigation.goBack()
                }}
                style={{
                  marginRight: 15,
                }}
              >
                <IconSymbol name="close" size={24} color={theme.colors.primary} />
              </TouchableOpacity>
            ),
          })}
        />
        <RootStack.Screen
          name="NewEntry"
          component={NewEntryScreen}
          options={{
            headerShown: false,
          }}
        />
      </RootStack.Navigator>
      <StatusBar style={theme.dark ? 'light' : 'dark'} />
    </PaperProvider>
  );
}