import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { useAuthStore } from './src/modules/auth/application/authStore';
import { useConfigStore } from './src/core/application/configStore';

const ConnectionSettings = ({ onBack }: { onBack: () => void }) => {
  const { apiUrl: currentApi, updateUrl: currentUpdate, setUrls } = useConfigStore();
  const [apiUrl, setApiUrl] = useState(currentApi);
  const [updateUrl, setUpdateUrl] = 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', 'Settings saved!', [{ text: 'OK', onPress: onBack }]);
  };

  return (
    <ScrollView contentContainerStyle={styles.scrollContainer}>
      <TouchableOpacity onPress={onBack} style={styles.backBtn}>
        <Text style={styles.backText}>← Back to Login</Text>
      </TouchableOpacity>
      <Text style={styles.label}>API Base URL</Text>
      <TextInput style={styles.input} value={apiUrl} onChangeText={setApiUrl} autoCapitalize="none" />
      <Text style={styles.label}>Update Server URL</Text>
      <TextInput style={styles.input} value={updateUrl} onChangeText={setUpdateUrl} autoCapitalize="none" />
      <TouchableOpacity style={styles.saveBtn} onPress={handleSave}>
        <Text style={styles.saveText}>Save Settings</Text>
      </TouchableOpacity>
    </ScrollView>
  );
};

export default function App() {
  const { login, isLoading, error, initialize, token } = useAuthStore();
  const { isConfigured, initialize: initConfig } = useConfigStore();
  const [showSettings, setShowSettings] = useState(false);

  useEffect(() => {
    initConfig();
    initialize().catch(e => console.error('Init failed', e));
  }, []);

  if (showSettings) {
    return <ConnectionSettings onBack={() => setShowSettings(false)} />;
  }

  return (
    <View style={styles.centerContainer}>
      <TouchableOpacity style={styles.settingsIcon} onPress={() => setShowSettings(true)}>
        <Text style={styles.settingsText}>Settings</Text>
      </TouchableOpacity>
      <Text style={styles.title}>Knot Messenger</Text>
      {!isConfigured && <Text style={styles.warningText}>Please configure connection first</Text>}
      {error && <Text style={styles.errorText}>{error}</Text>}
      {token ? (
        <Text style={styles.successText}>Logined!</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>
  );
}

const styles = StyleSheet.create({
  centerContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20, backgroundColor: '#fff' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  errorText: { color: 'red', marginBottom: 10 },
  successText: { color: 'green', fontSize: 18, fontWeight: 'bold' },
  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 },
  settingsIcon: { position: 'absolute', top: 50, right: 20, padding: 10 },
  settingsText: { color: '#007AFF', fontWeight: '600' },
  scrollContainer: { padding: 40, backgroundColor: '#fff', flex: 1 },
  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 },
  backBtn: { marginBottom: 20 },
  backText: { color: '#007AFF', fontSize: 16 }
});
