import { useEffect } from 'react';
import { useColorScheme } from 'react-native';
import { Redirect, Tabs } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useConvexAuth } from 'convex/react';

import { LoadingState } from '~/components/ui/loading-state';

const iconName = (route: string, focused: boolean) => {
  if (route === 'dashboard') return focused ? 'grid' : 'grid-outline';
  if (route === 'spoons') return focused ? 'git-branch' : 'git-branch-outline';
  if (route === 'threads')
    return focused ? 'chatbubbles' : 'chatbubbles-outline';
  return focused ? 'settings' : 'settings-outline';
};

const AppTabs = () => {
  const { isAuthenticated, isLoading } = useConvexAuth();
  const colorScheme = useColorScheme();

  useEffect(() => {
    // Keeps the auth subscription warm while tab routes mount.
  }, [isAuthenticated]);

  if (isLoading) return <LoadingState />;
  if (!isAuthenticated) return <Redirect href='/sign-in' />;

  return (
    <Tabs
      screenOptions={({ route }) => ({
        headerShown: false,
        tabBarActiveTintColor: '#0f766e',
        tabBarInactiveTintColor: colorScheme === 'dark' ? '#94a3b8' : '#64748b',
        tabBarStyle: {
          backgroundColor: colorScheme === 'dark' ? '#111827' : '#f8fafc',
          borderTopColor: colorScheme === 'dark' ? '#334155' : '#e2e8f0',
        },
        tabBarIcon: ({ color, focused, size }) => (
          <Ionicons
            color={color}
            name={iconName(route.name, focused)}
            size={size}
          />
        ),
      })}
    >
      <Tabs.Screen name='dashboard' options={{ title: 'Dashboard' }} />
      <Tabs.Screen name='spoons' options={{ title: 'Spoons' }} />
      <Tabs.Screen name='threads' options={{ title: 'Threads' }} />
      <Tabs.Screen name='workspace/[jobId]' options={{ href: null }} />
      <Tabs.Screen name='settings' options={{ title: 'Settings' }} />
    </Tabs>
  );
};

export default AppTabs;
