import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { Text } from 'react-native';

import { RecordingScreen }        from '../screens/RecordingScreen';
import { PostRecordingScreen }    from '../screens/PostRecordingScreen';
import { SensorPairingScreen }    from '../screens/SensorPairingScreen';
import { SavedRecordingsScreen }  from '../screens/SavedRecordingsScreen';
import { SettingsScreen }         from '../screens/SettingsScreen';
import { ActivityDetailScreen }   from '../screens/ActivityDetailScreen';
import { RootStackParamList, TabParamList } from '../types';
import { colors } from '../theme';
import { useTheme } from '../ThemeContext';

const Stack = createNativeStackNavigator<RootStackParamList>();
const Tab   = createBottomTabNavigator<TabParamList>();

const TAB_ICONS: Record<string, string> = {
  Recording: '◉',
  Saved:     '☰',
  Settings:  '⚙',
};

function Tabs() {
  const { accent } = useTheme();
  return (
    <Tab.Navigator
      screenOptions={({ route }) => ({
        headerStyle:            { backgroundColor: colors.bg },
        headerTintColor:        colors.text,
        tabBarStyle:            { backgroundColor: colors.surface, borderTopColor: colors.border },
        tabBarActiveTintColor:  accent,
        tabBarInactiveTintColor: colors.textMuted,
        tabBarIcon: ({ color }) => (
          <Text style={{ color, fontSize: 18 }}>{TAB_ICONS[route.name]}</Text>
        ),
      })}
    >
      <Tab.Screen name="Recording" component={RecordingScreen} />
      <Tab.Screen name="Saved"     component={SavedRecordingsScreen} />
      <Tab.Screen name="Settings"  component={SettingsScreen} />
    </Tab.Navigator>
  );
}

export function AppNavigator() {
  return (
    <NavigationContainer>
      <Stack.Navigator
        screenOptions={{
          headerStyle:   { backgroundColor: colors.bg },
          headerTintColor: colors.text,
          contentStyle:  { backgroundColor: colors.bg },
        }}
      >
        <Stack.Screen name="Tabs"          component={Tabs}               options={{ headerShown: false }} />
        <Stack.Screen name="PostRecording"  component={PostRecordingScreen}  options={{ title: 'Save Recording', presentation: 'modal' }} />
        <Stack.Screen name="SensorPairing" component={SensorPairingScreen}  options={{ title: 'Sensors',        presentation: 'modal' }} />
        <Stack.Screen name="ActivityDetail" component={ActivityDetailScreen} options={{ title: '' }} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
