"use client"
import { createStackNavigator } from "@react-navigation/stack"
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"
import { View, Text, Platform } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { useAuth } from "../contexts/AuthContext"
import { useOfflineMode } from "../contexts/OfflineModeContext"
import { COLORS } from "../constants/theme"
import Icon from "../../components/Icon"
import { useNavigation, NavigationContainerRef, CommonActions, getFocusedRouteNameFromRoute } from '@react-navigation/native';
import { useEffect, createRef } from 'react';

// Auth Screens
import LoginScreen from "../screens/auth/LoginScreen"

// Sync Screens
import InitialDataLoadScreen from "../screens/sync/InitialDataLoadScreen"
import CheckoutScreen from "../screens/sync/CheckoutScreen"

// Main Screens
import HomeScreen from "../screens/main/HomeScreen"
import RoutesScreen from "../screens/main/RoutesScreen"
import RoutingScreen from "../screens/main/RoutingScreen"
import DeliveriesScreen from "../screens/main/DeliveriesScreen"
import DeliveryDetailScreen from "../screens/main/DeliveryDetailScreen"
import CompleteDeliveryScreen from "../screens/main/CompleteDeliveryScreen"
import RescheduleDeliveryScreen from "../screens/main/RescheduleDeliveryScreen"
import DeliverySuccess from "../screens/main/DeliverySuccess"
import ProfileScreen from "../screens/main/ProfileScreen"

// Criação dos navegadores
const Stack = createStackNavigator()
const Tab = createBottomTabNavigator()
const DeliveriesStack = createStackNavigator()

// Criação do navigationRef para navegação global
export const navigationRef = createRef<NavigationContainerRef<any>>();

// Navegador de Autenticação
const AuthNavigator = () => {
	return (
		<Stack.Navigator screenOptions={{ headerShown: false }}>
			<Stack.Screen name="Login" component={LoginScreen} />
			<Stack.Screen name="InitialDataLoad" component={InitialDataLoadScreen} />
		</Stack.Navigator>
	)
}

// Navegador de Entregas (Stack)
const DeliveriesNavigator = () => {
	return (
		<DeliveriesStack.Navigator
			initialRouteName="DeliveriesList"
			screenOptions={{
				headerStyle: {
					backgroundColor: COLORS.primary,
				},
				headerTintColor: "#fff",
				headerTitleStyle: {
					fontWeight: "bold",
				},
			}}
		>
			<DeliveriesStack.Screen name="DeliveriesList" component={DeliveriesScreen} options={{ title: "Entregas", headerShown: false, headerStyle: { height: 50, backgroundColor: COLORS.primary }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold' } }} />
			<DeliveriesStack.Screen
				name="DeliveryDetail"
				component={DeliveryDetailScreen}
				options={{ title: "", headerShown: false, headerStyle: { height: 50, backgroundColor: COLORS.primary }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold' } }}
			/>
			<DeliveriesStack.Screen
				name="CompleteDelivery"
				component={CompleteDeliveryScreen}
				options={{ title: "", headerShown: false, headerStyle: { height: 50, backgroundColor: COLORS.primary }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold' } }}
			/>
			<DeliveriesStack.Screen
				name="RescheduleDelivery"
				component={RescheduleDeliveryScreen}
				options={{ title: "Reagendar Entrega", headerShown: true, headerStyle: { height: 50, backgroundColor: COLORS.primary }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold' } }}
			/>
			<DeliveriesStack.Screen
				name="DeliverySuccess"
				component={DeliverySuccess}
				options={{ title: "Entrega Completa", headerShown: true, headerStyle: { height: 50, backgroundColor: COLORS.primary }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold' } }}
			/>
			<DeliveriesStack.Screen
				name="Checkout"
				component={CheckoutScreen}
				options={{ title: "Sincronização", headerShown: false, headerStyle: { height: 50, backgroundColor: COLORS.primary }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold' } }}
			/>
		</DeliveriesStack.Navigator>
	)
}

// Navegador Principal (Tab)
const TabNavigator = () => {
	const insets = useSafeAreaInsets()
	
	return (
		<Tab.Navigator
			screenOptions={({ route }) => ({
				tabBarIcon: ({ focused, color, size }) => {
					// Usar ícones do componente Icon
					if (route.name === "Home") {
						return <Icon type="material" name="home" size={size} color={color} style={{ opacity: focused ? 1 : 0.7 }} />
					} else if (route.name === "Routes") {
						return <Icon type="material" name="map" size={size} color={color} style={{ opacity: focused ? 1 : 0.7 }} />
					} else if (route.name === "DeliveriesStack") {
						return (
							<Icon
								type="material"
								name="local-shipping"
								size={size}
								color={color}
								style={{ opacity: focused ? 1 : 0.7 }}
							/>
						)
					} else if (route.name === "Profile") {
						return (
							<Icon type="material" name="person" size={size} color={color} style={{ opacity: focused ? 1 : 0.7 }} />
						)
					}
					return null
				},
				tabBarActiveTintColor: COLORS.primary,
				tabBarInactiveTintColor: "gray",
				tabBarStyle: {
					paddingBottom: Platform.OS === 'android' ? 5 : Math.max(insets.bottom, 5),
					paddingTop: 5,
					height: Platform.OS === 'android' ? 60 : 60 + Math.max(insets.bottom, 0),
					backgroundColor: '#fff',
				},
				headerStyle: {
					backgroundColor: COLORS.primary,
				},
				headerTintColor: "#fff",
				headerTitleStyle: {
					fontWeight: "bold",
				},
			})}
		>
			<Tab.Screen name="Home" component={HomeScreen} options={{ title: "Início", headerShown: false }} />
			<Tab.Screen name="Routes" component={RoutesScreen} options={{ title: "Rotas", headerShown: false, headerStyle: {
				height: 50,
				backgroundColor: COLORS.primary,
			}, }} />
			<Tab.Screen
				name="DeliveriesStack"
				component={DeliveriesNavigator}
				options={({ route }) => {
					const routeName = getFocusedRouteNameFromRoute(route) ?? 'DeliveriesList';
					return {
						headerShown: false,
						title: "Entregas",
					};
				}}
				listeners={({ navigation, route }) => ({
					tabPress: (e) => {
						// Verificar qual rota está focada no stack de entregas
						const routeName = getFocusedRouteNameFromRoute(route) ?? 'DeliveriesList';
						
						// Se não está na tela inicial, resetar o stack
						if (routeName !== 'DeliveriesList') {
							// Prevenir navegação padrão
							e.preventDefault();
							
							// Obter o navigation do stack interno
							const deliveriesNavigation = navigation.getParent();
							if (deliveriesNavigation) {
								// Resetar o stack interno para a tela inicial
								deliveriesNavigation.dispatch(
									CommonActions.reset({
										index: 0,
										routes: [{ name: 'DeliveriesList' }],
									})
								);
							}
							
							// Navegar para a tab
							navigation.navigate('DeliveriesStack');
						}
					},
				})}
			/>
			<Tab.Screen name="Profile" component={ProfileScreen} options={{ title: "Perfil" }} />
		</Tab.Navigator>
	)
}

// Navegador Raiz
	const Navigation = () => {
		const { user, isLoading } = useAuth()
		const { isInitialDataLoaded, forceInitialLoad } = useOfflineMode()

	useEffect(() => {
		// Navigation state monitoring
	}, [user, isLoading, isInitialDataLoaded, forceInitialLoad]);

	if (isLoading) {
		return (
			<View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#FFFFFF" }}>
				<Text>Carregando...</Text>
			</View>
		)
	}

	
		return (
			<Stack.Navigator screenOptions={{ headerShown: false }}>
				{user ? (
					<>
						{(!isInitialDataLoaded || forceInitialLoad) ? (
							<Stack.Screen name="InitialDataLoad" component={InitialDataLoadScreen} />
						) : (
							<>
								<Stack.Screen name="Main" component={TabNavigator} />
								<Stack.Screen 
									name="Routing" 
									component={RoutingScreen} 
									options={{ 
										headerShown: false,
										presentation: 'modal'
									}} 
								/>
							</>
						)}
					</>
				) : (
					<Stack.Screen name="Auth" component={AuthNavigator} />
				)}
			</Stack.Navigator>
		)
}

export default Navigation