import {
  StatusBar,
  useColorScheme,
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  Alert, NativeModules
} from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { useState, useEffect } from 'react';
import Login from './src/components/Login';
import Register from './src/components/Register';
import { authAPI } from './src/services/authAPI';
import { networkService } from './src/services/networkService';
type Screen = 'login' | 'register' | 'home';
const { MyNativeModule } = NativeModules;

function App() {
  const isDarkMode = useColorScheme() === 'dark';
  const [currentScreen, setCurrentScreen] = useState<Screen>('login');
  const [isInitialized, setIsInitialized] = useState(false);
  const [isOnline, setIsOnline] = useState(true);
  const [currentUser, setCurrentUser] = useState<any>(null);

  // Initialize app
  useEffect(() => {
    initializeApp();
    console.log("MyNativeModule", MyNativeModule);
    MyNativeModule.greet("John").then((msg: any) => {
      console.log(msg);
    });

    // Listen for network changes
    const unsubscribe = networkService.addListener((networkState) => {
      setIsOnline(networkState.isConnected);
    });

    return unsubscribe;
  }, []);

  const initializeApp = async () => {
    try {
      console.log('Initializing app...');

      // Initialize authentication system
      await authAPI.initialize();

      // Check if user is already logged in
      const isLoggedIn = await authAPI.isLoggedIn();
      if (isLoggedIn) {
        const user = await authAPI.getCurrentUser();
        setCurrentUser(user);
        setCurrentScreen('home');
      }

      setIsInitialized(true);
      console.log('App initialized successfully');
    } catch (error) {
      console.error('App initialization error:', error);
      setIsInitialized(true); // Continue anyway
    }
  };

  const navigateToLogin = () => {
    setCurrentUser(null);
    setCurrentScreen('login');
  };

  const navigateToRegister = () => setCurrentScreen('register');

  const navigateToHome = async () => {
    const user = await authAPI.getCurrentUser();
    setCurrentUser(user);
    setCurrentScreen('home');
  };

  const handleLogout = async () => {
    try {
      await authAPI.logout();
      navigateToLogin();
      Alert.alert('Success', 'Logged out successfully');
    } catch (error) {
      console.error('Logout error:', error);
      Alert.alert('Error', 'Failed to logout');
    }
  };

  const showAppStatus = async () => {
    try {
      const status = await authAPI.getAppStatus();
      const statusMessage = `
Network: ${status.network.isOnline ? 'Online' : 'Offline'}
Users: ${status.storage.totalUsers}
Current User: ${status.authentication.currentUser || 'None'}
Logged In: ${status.authentication.isLoggedIn ? 'Yes' : 'No'}
      `.trim();

      Alert.alert('App Status', statusMessage);
    } catch (error) {
      Alert.alert('Error', 'Failed to get app status');
    }
  };

  const renderScreen = () => {
    switch (currentScreen) {
      case 'login':
        return (
          <Login
            onNavigateToRegister={navigateToRegister}
            onLoginSuccess={navigateToHome}
          />
        );
      case 'register':
        return (
          <Register
            onNavigateToLogin={navigateToLogin}
            onRegisterSuccess={navigateToHome}
          />
        );
      case 'home':
        return (
          <View style={styles.homeContainer}>
            <View style={styles.statusBar}>
              <Text style={styles.statusText}>
                {isOnline ? '🟢 Online' : '🔴 Offline'}
              </Text>
            </View>

            <Text style={styles.welcomeText}>
              Welcome, {currentUser?.fullName || 'User'}!
            </Text>

            <Text style={styles.emailText}>
              {currentUser?.email}
            </Text>

            <View style={styles.buttonContainer}>
              <TouchableOpacity style={styles.statusButton} onPress={showAppStatus}>
                <Text style={styles.buttonText}>App Status</Text>
              </TouchableOpacity>

              <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
                <Text style={styles.buttonText}>Logout</Text>
              </TouchableOpacity>
            </View>

            <Text style={styles.infoText}>
              {isOnline
                ? 'Your data is synced with the cloud'
                : 'Working offline - data saved locally'}
            </Text>
          </View>
        );
      default:
        return null;
    }
  };

  // Show loading screen while initializing
  if (!isInitialized) {
    return (
      <SafeAreaProvider>
        <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>Initializing...</Text>
        </View>
      </SafeAreaProvider>
    );
  }

  return (
    <SafeAreaProvider>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      {renderScreen()}
    </SafeAreaProvider>
  );
}

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
  },
  loadingText: {
    fontSize: 18,
    color: '#3bb6d8',
    fontWeight: '600',
  },
  homeContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
    padding: 20,
  },
  statusBar: {
    position: 'absolute',
    top: 60,
    right: 20,
    backgroundColor: 'white',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  statusText: {
    fontSize: 12,
    fontWeight: '600',
  },
  welcomeText: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
    textAlign: 'center',
  },
  emailText: {
    fontSize: 16,
    color: '#666',
    marginBottom: 40,
  },
  buttonContainer: {
    flexDirection: 'row',
    gap: 15,
    marginBottom: 30,
  },
  statusButton: {
    backgroundColor: '#3bb6d8',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 25,
  },
  logoutButton: {
    backgroundColor: '#ff6b6b',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 25,
  },
  buttonText: {
    color: 'white',
    fontWeight: '600',
    fontSize: 16,
  },
  infoText: {
    fontSize: 14,
    color: '#888',
    textAlign: 'center',
    fontStyle: 'italic',
  },
});

export default App;
