import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { useAuthStore } from '../../modules/auth/application/authStore';
import { ChatList } from '../../modules/chats/presentation/ChatList';
import { ChatRoom } from '../../modules/chats/presentation/ChatRoom';
import { View, Text, TouchableOpacity, StyleSheet, ActivityIndicator, TextInput, ScrollView, Alert } from 'react-native';
import { useConfigStore } from '../../core/application/configStore';

const Stack = createNativeStackNavigator();

// Temporary mock screens using the components we built

const HomeScreen = ({ navigation }: any) => {
  const { logout } = useAuthStore();
  
  // Mock data
  const mockChats = [
    {
      id: '1', type: 'personal' as const, name: 'Alice', avatar: null, createdAt: new Date().toISOString(), unreadCount: 2, members: [],
      messages: [{ id: 'm1', chatId: '1', senderId: 'user2', content: 'Hello!', createdAt: new Date().toISOString(), type: 'text', isEdited: false, isDeleted: false, sequenceId: 1, sender: { id: 'user2', username: 'alice', displayName: 'Alice' }, media: [], reactions: [], readBy: [] }]
    }
  ];

  return (
    <View style={styles.container}>
      <ChatList 
        chats={mockChats} 
        onChatPress={(chat) => navigation.navigate('ChatRoom', { chat })} 
      />
      <TouchableOpacity style={styles.logoutBtn} onPress={logout}>
        <Text style={styles.logoutText}>Logout</Text>
      </TouchableOpacity>
    </View>
  );
};

const ChatRoomScreen = ({ route }: any) => {
  const { chat } = route.params;
  const { user } = useAuthStore();
  
  const mockMessages = chat.messages || [];

  return (
    <View style={styles.container}>
      <ChatRoom 
        chat={chat} 
        messages={mockMessages} 
        currentUserId={user?.id || 'user1'} 
        onSendMessage={(text) => console.log('Sent:', text)} 
      />
    </View>
  );
};

const ConnectionSettingsScreen = ({ navigation }: any) => {
  const { apiUrl: currentApi, updateUrl: currentUpdate, setUrls } = useConfigStore();
  const [apiUrl, setApiUrl] = React.useState(currentApi);
  const [updateUrl, setUpdateUrl] = React.useState(currentUpdate);

  const handleSave = () => {
    if (!apiUrl.startsWith('http')) {
      Alert.alert('Error', 'API URL must start with http:// or https://');
      return;
    }
    setUrls(apiUrl, updateUrl);
    Alert.alert('Success', 'Connection settings saved!', [{ text: 'OK', onPress: () => navigation.goBack() }]);
  };

  return (
    <ScrollView contentContainerStyle={styles.scrollContainer}>
      <Text style={styles.label}>API Base URL</Text>
      <TextInput
        style={styles.input}
        value={apiUrl}
        onChangeText={setApiUrl}
        placeholder="https://your-server.com/api"
        autoCapitalize="none"
      />
      
      <Text style={styles.label}>Update Server URL (OTA)</Text>
      <TextInput
        style={styles.input}
        value={updateUrl}
        onChangeText={setUpdateUrl}
        placeholder="https://your-server.com/api/v1/updates"
        autoCapitalize="none"
      />

      <TouchableOpacity style={styles.saveBtn} onPress={handleSave}>
        <Text style={styles.saveText}>Save Settings</Text>
      </TouchableOpacity>
    </ScrollView>
  );
};

const LoginScreen = ({ navigation }: any) => {
  const { login, isLoading, error } = useAuthStore();
  const { isConfigured } = useConfigStore();

  return (
    <View style={styles.centerContainer}>
      <TouchableOpacity 
        style={styles.settingsIcon} 
        onPress={() => navigation.navigate('Settings')}
      >
        <Text style={styles.settingsText}>Settings</Text>
      </TouchableOpacity>

      <Text style={styles.title}>Knot Messenger</Text>
      {!isConfigured && (
        <Text style={styles.warningText}>Please configure connection settings first</Text>
      )}
      {error && <Text style={styles.errorText}>{error}</Text>}
      <TouchableOpacity 
        style={[styles.loginBtn, !isConfigured && styles.disabledBtn]} 
        onPress={() => login('test', 'password')}
        disabled={isLoading || !isConfigured}
      >
        {isLoading ? (
          <ActivityIndicator color="#fff" />
        ) : (
          <Text style={styles.loginText}>Login</Text>
        )}
      </TouchableOpacity>
    </View>
  );
};

export const AppNavigator = () => {
  const { token } = useAuthStore();

  return (
    <NavigationContainer>
      <Stack.Navigator>
        {!token ? (
          <>
            <Stack.Screen name="Login" component={LoginScreen} options={{ headerShown: false }} />
            <Stack.Screen name="Settings" component={ConnectionSettingsScreen} options={{ title: 'Connection Settings' }} />
          </>
        ) : (
          <>
            <Stack.Screen name="Home" component={HomeScreen} options={{ title: 'Chats' }} />
            <Stack.Screen 
              name="ChatRoom" 
              component={ChatRoomScreen} 
              options={({ route }: any) => ({ title: route.params.chat.name || 'Chat' })} 
            />
          </>
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff' },
  centerContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  errorText: { color: 'red', marginBottom: 10 },
  warningText: { color: '#FFA500', marginBottom: 15, textAlign: 'center' },
  loginBtn: { backgroundColor: '#007AFF', padding: 15, borderRadius: 8, width: '100%', alignItems: 'center' },
  disabledBtn: { backgroundColor: '#ccc' },
  loginText: { color: '#fff', fontWeight: 'bold', fontSize: 16 },
  logoutBtn: { padding: 15, alignItems: 'center', borderTopWidth: 1, borderColor: '#eee' },
  logoutText: { color: 'red', fontSize: 16 },
  settingsIcon: { position: 'absolute', top: 50, right: 20, padding: 10 },
  settingsText: { color: '#007AFF', fontWeight: '600' },
  scrollContainer: { padding: 20 },
  label: { fontSize: 14, fontWeight: '600', color: '#666', marginBottom: 8, marginTop: 15 },
  input: { backgroundColor: '#f5f5f5', padding: 12, borderRadius: 8, fontSize: 16, borderWidth: 1, borderColor: '#ddd' },
  saveBtn: { backgroundColor: '#34C759', padding: 15, borderRadius: 8, marginTop: 30, alignItems: 'center' },
  saveText: { color: '#fff', fontWeight: 'bold', fontSize: 16 }
});
