import React, { useEffect, useState } from 'react';
import {
  StatusBar,
  useColorScheme,
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  Alert,
  NativeModules,
  Image,
  ScrollView,
} from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';

import Login from './src/components/Login';
import Register from './src/components/Register';
import { authAPI } from './src/services/authAPI';
import { networkService } from './src/services/networkService';
import { ScannerScreen } from './src/screens/ScannerScreen';

type Screen = 'login' | 'register' | 'home' | 'scanner';

// ✅ Correct native module
const { ICameraSDK } = NativeModules;

function App(): JSX.Element {
  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);
  const [qrCode, setQrCode] = useState<string | null>(null);
  const [isGeneratingQR, setIsGeneratingQR] = useState(false);
  const [scannedCodes, setScannedCodes] = useState<any[]>([]);

  /* -------------------- INIT -------------------- */
  useEffect(() => {
    initializeApp();

    console.log('ICameraSDK:', ICameraSDK);
    ICameraSDK?.greet?.('John')
      .then((msg: string) => console.log(msg))
      .catch(console.error);

    const unsubscribe = networkService.addListener(networkState => {
      setIsOnline(networkState.isConnected);
    });

    return unsubscribe;
  }, []);

  const initializeApp = async () => {
    try {
      await authAPI.initialize();
      const loggedIn = await authAPI.isLoggedIn();
      if (loggedIn) {
        const user = await authAPI.getCurrentUser();
        setCurrentUser(user);
        setCurrentScreen('home');
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsInitialized(true);
    }
  };

  /* -------------------- NAVIGATION -------------------- */
  const navigateToLogin = () => {
    setCurrentUser(null);
    setQrCode(null);
    setCurrentScreen('login');
  };

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

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

  const openScanner = () => {
    setCurrentScreen('scanner');
  };

  /* -------------------- ACTIONS -------------------- */
  const handleLogout = async () => {
    try {
      await authAPI.logout();
      navigateToLogin();
      Alert.alert('Success', 'Logged out successfully');
    } catch {
      Alert.alert('Error', 'Failed to logout');
    }
  };

  const generateQRCode = async () => {
    if (!currentUser?.email || !ICameraSDK) {
      Alert.alert('Error', 'Native QR module not available');
      return;
    }

    setIsGeneratingQR(true);
    try {
      const qrData = `User: ${currentUser.fullName}\nEmail: ${currentUser.email}`;
      const base64 = await ICameraSDK.generateQRCode(qrData, 300, 300);
      setQrCode(base64);
    } catch (e) {
      console.error(e);
      Alert.alert('Error', 'QR generation failed');
    } finally {
      setIsGeneratingQR(false);
    }
  };

  const handleScanResult = (result: any) => {
    setScannedCodes(prev => [
      {
        code: result.code,
        format: result.format,
        timestamp: new Date().toLocaleTimeString(),
      },
      ...prev,
    ]);

    Alert.alert(
      'Scanned',
      `Code: ${result.code}\nFormat: ${result.format}`,
      [{ text: 'OK', onPress: () => setCurrentScreen('home') }]
    );
  };

  /* -------------------- RENDER -------------------- */
  const renderScreen = () => {
    switch (currentScreen) {
      case 'login':
        return (
          <Login
            onNavigateToRegister={navigateToRegister}
            onLoginSuccess={navigateToHome}
          />
        );

      case 'register':
        return (
          <Register
            onNavigateToLogin={navigateToLogin}
            onRegisterSuccess={navigateToHome}
          />
        );

      case 'scanner':
        return (
          <ScannerScreen
            presignedUrl="https://your-backend-presigned-url.com"
            onScan={handleScanResult}
          />
        );

      case 'home':
        return (
          <ScrollView
            style={styles.homeContainer}
            contentContainerStyle={styles.scrollContent}
          >
            <Text style={styles.welcomeText}>
              Welcome, {currentUser?.fullName || 'User'}
            </Text>

            {qrCode && <Image source={{ uri: qrCode }} style={styles.qrImage} />}

            <TouchableOpacity style={styles.button} onPress={openScanner}>
              <Text style={styles.buttonText}>Scan QR / Barcode</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.qrButton]}
              onPress={generateQRCode}
              disabled={isGeneratingQR}
            >
              <Text style={styles.buttonText}>
                {isGeneratingQR ? 'Generating...' : 'Generate QR'}
              </Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.logoutButton]}
              onPress={handleLogout}
            >
              <Text style={styles.buttonText}>Logout</Text>
            </TouchableOpacity>
          </ScrollView>
        );
    }
  };

  if (!isInitialized) {
    return (
      <SafeAreaProvider>
        <View style={styles.loading}>
          <Text>Initializing...</Text>
        </View>
      </SafeAreaProvider>
    );
  }

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

export default App;

/* -------------------- STYLES -------------------- */

const styles = StyleSheet.create({
  loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  homeContainer: { flex: 1 },
  scrollContent: { alignItems: 'center', padding: 20 },
  welcomeText: { fontSize: 24, fontWeight: '700', marginBottom: 20 },
  qrImage: { width: 300, height: 300, marginBottom: 20 },
  button: {
    backgroundColor: '#6366f1',
    padding: 14,
    borderRadius: 18,
    marginBottom: 12,
    minWidth: 220,
    alignItems: 'center',
  },
  qrButton: { backgroundColor: '#10b981' },
  logoutButton: { backgroundColor: '#ef4444' },
  buttonText: { color: '#fff', fontWeight: '600' },
});
