import { useEffect, useState } from 'react';
import {
  View, Text, Switch, TouchableOpacity, StyleSheet, ScrollView, Alert,
} from 'react-native';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/api/client';
import { getSetting, setSetting } from '@/db/local';
import { getStoredUser, clearAuth } from '@/lib/auth';
import { Colors, Spacing, Typography, Radius } from '@/theme';
import type { AuthUser, UserSettings } from '@/types';

const DEFAULT_SETTINGS: UserSettings = {
  languageMix: 'alternate',
  difficultyMin: 1,
  difficultyMax: 5,
  theme: 'system',
  posColoring: true,
  interlinearGloss: false,
  dailyGoal: 1,
};

export default function SettingsScreen() {
  const qc = useQueryClient();
  const [user, setUser] = useState<AuthUser | null>(null);
  const [settings, setSettings] = useState<UserSettings>(DEFAULT_SETTINGS);

  // Load user from secure store
  useEffect(() => {
    getStoredUser().then(setUser);
  }, []);

  // Load settings from local DB
  useEffect(() => {
    getSetting('user_settings').then((raw) => {
      if (raw) setSettings(JSON.parse(raw));
    });
  }, []);

  async function updateSetting<K extends keyof UserSettings>(
    key: K,
    value: UserSettings[K],
  ) {
    const updated = { ...settings, [key]: value };
    setSettings(updated);
    await setSetting('user_settings', JSON.stringify(updated));
    // Sync to server if online
    api.patch('/api/user/settings', { [key]: value }).catch(() => {});
  }

  function confirmSignOut() {
    Alert.alert('Sign out', 'Sign out of ClassicsLens?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Sign out',
        style: 'destructive',
        onPress: async () => {
          await api.post('/api/auth/logout').catch(() => {});
          await clearAuth();
          qc.clear();
          setUser(null);
        },
      },
    ]);
  }

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      {/* Account */}
      {user && (
        <Section title="Account">
          <Row label="Email">
            <Text style={styles.valueText}>{user.email}</Text>
          </Row>
          <Row label="Plan">
            <Text style={[styles.valueText, styles.tier]}>{user.tier}</Text>
          </Row>
          <TouchableOpacity onPress={confirmSignOut} style={styles.signOutButton}>
            <Text style={styles.signOutText}>Sign out</Text>
          </TouchableOpacity>
        </Section>
      )}

      {/* Reading preferences */}
      <Section title="Reading">
        <ToggleRow
          label="POS coloring"
          description="Color-code words by part of speech"
          value={settings.posColoring}
          onChange={(v) => updateSetting('posColoring', v)}
        />
        <ToggleRow
          label="Interlinear gloss"
          description="Show short definition below each word"
          value={settings.interlinearGloss}
          onChange={(v) => updateSetting('interlinearGloss', v)}
        />
      </Section>

      {/* Language */}
      <Section title="Language">
        {(
          [
            ['alternate', 'Alternating (Latin + Greek)'],
            ['latin_only', 'Latin only'],
            ['greek_only', 'Greek only'],
            ['mostly_latin', 'Mostly Latin'],
            ['mostly_greek', 'Mostly Greek'],
          ] as [UserSettings['languageMix'], string][]
        ).map(([value, label]) => (
          <TouchableOpacity
            key={value}
            style={styles.radioRow}
            onPress={() => updateSetting('languageMix', value)}
          >
            <View style={[
              styles.radioCircle,
              settings.languageMix === value && styles.radioCircleActive,
            ]} />
            <Text style={styles.radioLabel}>{label}</Text>
          </TouchableOpacity>
        ))}
      </Section>

      {/* App info */}
      <Section title="About">
        <Row label="Version"><Text style={styles.valueText}>1.0.0</Text></Row>
        <Row label="Build"><Text style={styles.valueText}>offline-first</Text></Row>
      </Section>
    </ScrollView>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <View style={styles.section}>
      <Text style={styles.sectionTitle}>{title}</Text>
      <View style={styles.sectionBody}>{children}</View>
    </View>
  );
}

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <View style={styles.row}>
      <Text style={styles.rowLabel}>{label}</Text>
      {children}
    </View>
  );
}

function ToggleRow({
  label, description, value, onChange,
}: {
  label: string; description: string;
  value: boolean; onChange: (v: boolean) => void;
}) {
  return (
    <View style={styles.row}>
      <View style={{ flex: 1 }}>
        <Text style={styles.rowLabel}>{label}</Text>
        <Text style={styles.rowDesc}>{description}</Text>
      </View>
      <Switch
        value={value}
        onValueChange={onChange}
        trackColor={{ false: Colors.border, true: Colors.primary }}
        thumbColor="#fff"
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.background },
  content: { padding: Spacing.lg, gap: Spacing.xl },
  section: { gap: Spacing.sm },
  sectionTitle: {
    fontSize: Typography.size.xs,
    fontWeight: Typography.weight.semibold,
    color: Colors.textMuted,
    textTransform: 'uppercase',
    letterSpacing: 1,
    paddingHorizontal: Spacing.sm,
  },
  sectionBody: {
    backgroundColor: Colors.surface,
    borderRadius: Radius.lg,
    borderWidth: 1,
    borderColor: Colors.border,
    overflow: 'hidden',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: Spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: Colors.border,
  },
  rowLabel: {
    fontSize: Typography.size.base,
    color: Colors.text,
    fontWeight: Typography.weight.medium,
  },
  rowDesc: {
    fontSize: Typography.size.xs,
    color: Colors.textMuted,
    marginTop: 2,
  },
  valueText: { fontSize: Typography.size.sm, color: Colors.textMuted },
  tier: {
    textTransform: 'capitalize',
    color: Colors.accent,
    fontWeight: Typography.weight.semibold,
  },
  radioRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.md,
    padding: Spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: Colors.border,
  },
  radioCircle: {
    width: 18, height: 18,
    borderRadius: 9,
    borderWidth: 2,
    borderColor: Colors.border,
  },
  radioCircleActive: { borderColor: Colors.primary, backgroundColor: Colors.primary },
  radioLabel: { fontSize: Typography.size.base, color: Colors.text },
  signOutButton: {
    padding: Spacing.md,
    alignItems: 'center',
  },
  signOutText: {
    color: Colors.error,
    fontWeight: Typography.weight.medium,
    fontSize: Typography.size.base,
  },
});
