/**
 * LnP360 Mobile App
 * Kenyan Pension & Life Insurance Management System
 * Main App Entry Point
 */

import React, { useEffect, useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { View, ActivityIndicator, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Toast from 'react-native-toast-message';

// Screens
import LoginScreen from './src/screens/auth/LoginScreen';
import DashboardScreen from './src/screens/dashboard/DashboardScreen';
import ContributionsScreen from './src/screens/contributions/ContributionsScreen';
import PoliciesScreen from './src/screens/policies/PoliciesScreen';
import WithdrawalsScreen from './src/screens/withdrawals/WithdrawalsScreen';
import ProfileScreen from './src/screens/profile/ProfileScreen';
import ContributionDetailsScreen from './src/screens/contributions/ContributionDetailsScreen';
import PolicyDetailsScreen from './src/screens/policies/PolicyDetailsScreen';
import WithdrawalRequestScreen from './src/screens/withdrawals/WithdrawalRequestScreen';
import StatementScreen from './src/screens/statements/StatementScreen';
import BeneficiariesScreen from './src/screens/beneficiaries/BeneficiariesScreen';
import PremiumsScreen from './src/screens/premiums/PremiumsScreen';
import ClaimsScreen from './src/screens/claims/ClaimsScreen';

// Services
import { AuthService } from './src/services/AuthService';

const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();

// Main Tab Navigator
function MainTabs() {
  return (
    <Tab.Navigator
      screenOptions={({ route }) => ({
        tabBarIcon: ({ focused, color, size }) => {
          let iconName;

          if (route.name === 'Dashboard') {
            iconName = focused ? 'view-dashboard' : 'view-dashboard-outline';
          } else if (route.name === 'Contributions') {
            iconName = focused ? 'wallet' : 'wallet-outline';
          } else if (route.name === 'Policies') {
            iconName = focused ? 'shield-account' : 'shield-account-outline';
          } else if (route.name === 'Withdrawals') {
            iconName = focused ? 'cash-multiple' : 'cash-multiple';
          } else if (route.name === 'Profile') {
            iconName = focused ? 'account' : 'account-outline';
          }

          return <Icon name={iconName} size={size} color={color} />;
        },
        tabBarActiveTintColor: '#2563eb',
        tabBarInactiveTintColor: '#6b7280',
        headerShown: false,
      })}
    >
      <Tab.Screen name="Dashboard" component={DashboardScreen} />
      <Tab.Screen name="Contributions" component={ContributionsScreen} />
      <Tab.Screen name="Policies" component={PoliciesScreen} />
      <Tab.Screen name="Withdrawals" component={WithdrawalsScreen} />
      <Tab.Screen name="Profile" component={ProfileScreen} />
    </Tab.Navigator>
  );
}

// Main App Component
export default function App() {
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    checkAuthStatus();
  }, []);

  const checkAuthStatus = async () => {
    try {
      const token = await AsyncStorage.getItem('auth_token');
      if (token) {
        // Verify token is still valid
        const isValid = await AuthService.verifyToken(token);
        setIsAuthenticated(isValid);
      }
    } catch (error) {
      console.error('Auth check error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#2563eb" />
      </View>
    );
  }

  return (
    <NavigationContainer>
      <Stack.Navigator screenOptions={{ headerShown: false }}>
        {!isAuthenticated ? (
          <>
            <Stack.Screen name="Login" component={LoginScreen} />
          </>
        ) : (
          <>
            <Stack.Screen name="MainTabs" component={MainTabs} />
            <Stack.Screen 
              name="ContributionDetails" 
              component={ContributionDetailsScreen}
              options={{ headerShown: true, title: 'Contribution Details' }}
            />
            <Stack.Screen 
              name="PolicyDetails" 
              component={PolicyDetailsScreen}
              options={{ headerShown: true, title: 'Policy Details' }}
            />
            <Stack.Screen 
              name="WithdrawalRequest" 
              component={WithdrawalRequestScreen}
              options={{ headerShown: true, title: 'Request Withdrawal' }}
            />
            <Stack.Screen 
              name="Statement" 
              component={StatementScreen}
              options={{ headerShown: true, title: 'Statement' }}
            />
            <Stack.Screen 
              name="Beneficiaries" 
              component={BeneficiariesScreen}
              options={{ headerShown: true, title: 'Beneficiaries' }}
            />
            <Stack.Screen 
              name="Premiums" 
              component={PremiumsScreen}
              options={{ headerShown: true, title: 'Premium Payments' }}
            />
            <Stack.Screen 
              name="Claims" 
              component={ClaimsScreen}
              options={{ headerShown: true, title: 'Claims' }}
            />
          </>
        )}
      </Stack.Navigator>
      <Toast />
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffffff',
  },
});
