import { Tabs } from 'expo-router';
import React from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { TabBarIcon } from '@/components/TabBarIcon';
import { useSettings } from '@/theme';
import { setLastVisitedTab } from '@/utils/tabHistory';

export default function TabLayout() {
  const { theme } = useSettings();
  const insets = useSafeAreaInsets();

  return (
    <Tabs
      screenOptions={{
        tabBarActiveTintColor: theme.accent,
        tabBarInactiveTintColor: theme.text,
        tabBarStyle: {
          backgroundColor: theme.tabBarBg,
          borderTopWidth: 1,
          borderTopColor: theme.border,
          height: 68 + insets.bottom,
          paddingBottom: insets.bottom,
          paddingTop: 6,
          elevation: 8,
          shadowColor: '#000',
          shadowOffset: { width: 0, height: -2 },
          shadowOpacity: 0.08,
          shadowRadius: 8,
        },
        tabBarItemStyle: {
          paddingVertical: 0,
        },
        tabBarLabelStyle: {
          fontSize: 11,
          fontWeight: '700',
        },
        headerShown: false,
        sceneStyle: { backgroundColor: theme.background },
      }}
      screenListeners={({ route }) => ({
        focus: () => {
          if (route.name !== 'settings') {
            setLastVisitedTab(route.name);
          }
        },
      })}
    >
      <Tabs.Screen
        name="index"
        options={{
          title: 'ToDo',
          tabBarIcon: ({ color, focused }) => (
            <TabBarIcon name="checklist" focused={focused} color={color} size={26} />
          ),
        }}
      />
      <Tabs.Screen
        name="calendar"
        options={{
          title: 'Calendar',
          tabBarIcon: ({ color, focused }) => (
            <TabBarIcon name="calendar" focused={focused} color={color} size={26} />
          ),
        }}
      />
      <Tabs.Screen
        name="stats"
        options={{
          title: 'Stats',
          tabBarIcon: ({ color, focused }) => (
            <TabBarIcon name="stats" focused={focused} color={color} size={26} />
          ),
        }}
      />
      <Tabs.Screen
        name="settings"
        options={{
          title: 'Settings',
          tabBarIcon: ({ color, focused }) => (
            <TabBarIcon name="gear" focused={focused} color={color} size={26} />
          ),
        }}
      />
    </Tabs>
  );
}