import { useState, useEffect } from 'react';
import { StyleSheet, View, Text, TextInput, TouchableOpacity, Switch, ScrollView } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Stack } from 'expo-router';
import { useKeepAwake } from 'expo-keep-awake';
// We will import socket logic later

export default function SettingsScreen() {
  useKeepAwake(); // Keep the screen awake

  const [endpoint, setEndpoint] = useState('http://192.168.1.x:3001');
  const [login, setLogin] = useState('');
  const [password, setPassword] = useState('');
  const [isSaved, setIsSaved] = useState(false);

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

  const loadSettings = async () => {
    try {
      const savedEndpoint = await AsyncStorage.getItem('endpoint');
      const savedLogin = await AsyncStorage.getItem('login');
      const savedPassword = await AsyncStorage.getItem('password');
      
      if (savedEndpoint) setEndpoint(savedEndpoint);
      if (savedLogin) setLogin(savedLogin);
      if (savedPassword) setPassword(savedPassword);
    } catch (e) {
      console.error('Failed to load settings', e);
    }
  };

  const saveSettings = async () => {
    try {
      await AsyncStorage.setItem('endpoint', endpoint);
      await AsyncStorage.setItem('login', login);
      await AsyncStorage.setItem('password', password);
      setIsSaved(true);
      setTimeout(() => setIsSaved(false), 2000);
      
      // In a real app, we would trigger a reconnect here
    } catch (e) {
      console.error('Failed to save settings', e);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.section}>
        <Text style={styles.label}>Backend Endpoint</Text>
        <TextInput
          style={styles.input}
          value={endpoint}
          onChangeText={setEndpoint}
          placeholder="http://192.168.1.x:3001"
          autoCapitalize="none"
          keyboardType="url"
        />
      </View>

      <View style={styles.section}>
        <Text style={styles.label}>Login</Text>
        <TextInput
          style={styles.input}
          value={login}
          onChangeText={setLogin}
          placeholder="admin"
          autoCapitalize="none"
        />
      </View>

      <View style={styles.section}>
        <Text style={styles.label}>Password</Text>
        <TextInput
          style={styles.input}
          value={password}
          onChangeText={setPassword}
          placeholder="admin123"
          secureTextEntry
        />
      </View>

      <TouchableOpacity style={styles.button} onPress={saveSettings}>
        <Text style={styles.buttonText}>{isSaved ? 'Saved!' : 'Save Settings'}</Text>
      </TouchableOpacity>

      <View style={styles.infoBox}>
        <Text style={styles.infoText}>
          Note: This app will keep the screen awake while running to ensure background SMS sending works reliably.
        </Text>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  section: {
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 8,
    color: '#333',
  },
  input: {
    backgroundColor: '#fff',
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
  },
  button: {
    backgroundColor: '#208AEF',
    padding: 15,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 10,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  infoBox: {
    marginTop: 30,
    padding: 15,
    backgroundColor: '#e8f4fd',
    borderRadius: 8,
    borderLeftWidth: 4,
    borderLeftColor: '#208AEF',
  },
  infoText: {
    color: '#555',
    fontSize: 14,
    lineHeight: 20,
  }
});
