import { useState, useEffect } from 'react';
import { StyleSheet, View, Text, TextInput, TouchableOpacity, ScrollView } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Stack, router } from 'expo-router';
import { useKeepAwake } from 'expo-keep-awake';

const COLORS = {
  background: '#121416',
  surface: '#1e2022',
  surfaceHigh: '#282a2c',
  primary: '#fefcff',
  onPrimary: '#213148',
  text: '#e2e2e5',
  textMuted: '#c5c6cd',
  success: '#69fc9b',
  error: '#ffb4ab',
  border: '#44474d',
};

export default function SettingsScreen() {
  useKeepAwake();

  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);
    } catch (e) {
      console.error('Failed to save settings', e);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <Stack.Screen options={{ headerShown: false }} />
      
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <Text style={styles.backIcon}>←</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Settings</Text>
        <View style={{ width: 40 }} />
      </View>

      <ScrollView style={styles.scrollContent} contentContainerStyle={styles.scrollContentContainer}>
        
        <View style={styles.card}>
          <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"
              placeholderTextColor={COLORS.border}
              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"
              placeholderTextColor={COLORS.border}
              autoCapitalize="none"
            />
          </View>

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

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

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 16,
    marginTop: 8,
  },
  backButton: {
    padding: 8,
    width: 40,
  },
  backIcon: {
    color: COLORS.text,
    fontSize: 24,
  },
  headerTitle: {
    color: COLORS.text,
    fontSize: 20,
    fontWeight: 'bold',
  },
  scrollContent: {
    flex: 1,
  },
  scrollContentContainer: {
    padding: 24,
  },
  card: {
    backgroundColor: COLORS.surface,
    borderRadius: 24,
    padding: 24,
    marginBottom: 24,
  },
  section: {
    marginBottom: 20,
  },
  label: {
    fontSize: 14,
    fontWeight: '600',
    marginBottom: 8,
    color: COLORS.text,
  },
  input: {
    backgroundColor: COLORS.background,
    borderWidth: 1,
    borderColor: COLORS.border,
    borderRadius: 12,
    padding: 16,
    fontSize: 16,
    color: COLORS.text,
  },
  button: {
    backgroundColor: COLORS.primary,
    padding: 16,
    borderRadius: 9999,
    alignItems: 'center',
    marginBottom: 24,
  },
  buttonText: {
    color: COLORS.onPrimary,
    fontSize: 16,
    fontWeight: 'bold',
  },
  infoBox: {
    flexDirection: 'row',
    padding: 16,
    backgroundColor: COLORS.surfaceHigh,
    borderRadius: 16,
    alignItems: 'center',
  },
  infoIcon: {
    fontSize: 20,
    marginRight: 12,
  },
  infoText: {
    flex: 1,
    color: COLORS.textMuted,
    fontSize: 13,
    lineHeight: 20,
  }
});