/**
 * Settings — app configuration, profile, logout.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Switch,
  Alert,
  Linking,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../themes/ThemeProvider';
import { getStoredUser, logout, AuthUser } from '../services/auth';
import { clearAllCache, getQueueLength, processQueue } from '../services/offline';
import { clearAllNotifications } from '../services/notifications';

export default function Settings({ navigation }: any) {
  const { theme } = useTheme();
  const [user, setUser] = useState<AuthUser | null>(null);
  const [offlineCount, setOfflineCount] = useState(0);
  const [pushEnabled, setPushEnabled] = useState(true);
  const [offlineMode, setOfflineMode] = useState(true);

  useEffect(() => {
    (async () => {
      const u = await getStoredUser();
      setUser(u);
      const count = await getQueueLength();
      setOfflineCount(count);
    })();
  }, []);

  const handleLogout = () => {
    Alert.alert('Sign Out', 'Are you sure you want to sign out?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Sign Out',
        style: 'destructive',
        onPress: async () => {
          await logout();
          // Navigation reset would happen in App.tsx auth state listener
        },
      },
    ]);
  };

  const handleSyncNow = async () => {
    const result = await processQueue();
    Alert.alert('Sync Complete', `Processed: ${result.processed}, Failed: ${result.failed}`);
    setOfflineCount(await getQueueLength());
  };

  const handleClearCache = () => {
    Alert.alert('Clear Cache', 'This will remove cached data. You\'ll need an internet connection to reload.', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Clear',
        style: 'destructive',
        onPress: async () => {
          await clearAllCache();
          Alert.alert('Done', 'Cache cleared');
        },
      },
    ]);
  };

  const Section = ({ title, children }: { title: string; children: React.ReactNode }) => (
    <View style={styles.section}>
      <Text style={[styles.sectionTitle, { color: theme.colors.textSecondary }]}>{title}</Text>
      <View style={[styles.sectionContent, { backgroundColor: theme.colors.card }]}>{children}</View>
    </View>
  );

  const Row = ({
    label,
    value,
    onPress,
    destructive,
  }: {
    label: string;
    value?: string;
    onPress?: () => void;
    destructive?: boolean;
  }) => (
    <TouchableOpacity
      style={[styles.row, { borderBottomColor: theme.colors.border }]}
      onPress={onPress}
      disabled={!onPress}
    >
      <Text style={[styles.rowLabel, { color: destructive ? theme.colors.error : theme.colors.text }]}>
        {label}
      </Text>
      {value && <Text style={[styles.rowValue, { color: theme.colors.textSecondary }]}>{value}</Text>}
    </TouchableOpacity>
  );

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <ScrollView>
        {/* Profile */}
        {user && (
          <Section title="PROFILE">
            <Row label="Name" value={user.name} />
            <Row label="Email" value={user.email} />
            <Row label="Role" value={user.role} />
          </Section>
        )}

        {/* Notifications */}
        <Section title="NOTIFICATIONS">
          <View style={[styles.row, { borderBottomColor: theme.colors.border }]}>
            <Text style={[styles.rowLabel, { color: theme.colors.text }]}>Push Notifications</Text>
            <Switch
              value={pushEnabled}
              onValueChange={setPushEnabled}
              trackColor={{ false: theme.colors.border, true: theme.colors.primary }}
              thumbColor="#FFF"
            />
          </View>
          <Row label="Clear All Notifications" onPress={async () => {
            await clearAllNotifications();
            Alert.alert('Done', 'All notifications cleared');
          }} />
        </Section>

        {/* Offline & Sync */}
        <Section title="OFFLINE & SYNC">
          <View style={[styles.row, { borderBottomColor: theme.colors.border }]}>
            <Text style={[styles.rowLabel, { color: theme.colors.text }]}>Offline Mode</Text>
            <Switch
              value={offlineMode}
              onValueChange={setOfflineMode}
              trackColor={{ false: theme.colors.border, true: theme.colors.primary }}
              thumbColor="#FFF"
            />
          </View>
          <Row
            label="Pending Sync Actions"
            value={String(offlineCount)}
            onPress={offlineCount > 0 ? handleSyncNow : undefined}
          />
          <Row label="Clear Cache" onPress={handleClearCache} />
        </Section>

        {/* About */}
        <Section title="ABOUT">
          <Row label="Version" value="1.0.0" />
          <Row label="Build" value="16-REACT-NATIVE-MOBILE" />
          <Row
            label="Privacy Policy"
            onPress={() => Linking.openURL('https://fogbreak.io/privacy')}
          />
          <Row
            label="Terms of Service"
            onPress={() => Linking.openURL('https://fogbreak.io/terms')}
          />
        </Section>

        {/* Account */}
        <Section title="ACCOUNT">
          <Row label="Sign Out" onPress={handleLogout} destructive />
        </Section>

        <View style={styles.bottomPad} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  section: { marginTop: 24 },
  sectionTitle: {
    fontSize: 12,
    fontWeight: '600',
    paddingHorizontal: 16,
    paddingBottom: 6,
    letterSpacing: 0.5,
  },
  sectionContent: { borderTopWidth: StyleSheet.hairlineWidth, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: '#E5E7EB' },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  rowLabel: { fontSize: 15 },
  rowValue: { fontSize: 15 },
  bottomPad: { height: 40 },
});
