import React, { useEffect, useState } from "react";
import { View, Text, StyleSheet, ScrollView, Switch, TouchableOpacity, Alert, TextInput } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { colors, spacing, radii } from "@/theme";
import { useAuth } from "@/auth/AuthProvider";
import {
  DEFAULT_RULES,
  readRules,
  writeRules,
  readPushEnabled,
  writePushEnabled,
  ensureNotificationPermission,
  fireTestNotification,
  AlertRulesState,
} from "@/lib/alerts";
import { registerBackgroundAlerts, unregisterBackgroundAlerts } from "@/lib/backgroundAlerts";

/**
 * Settings screen. Currently owns:
 *   - Push alerts on/off (spread + latency), permission handshake,
 *     and background-fetch task lifecycle.
 *   - Global thresholds (matches web app defaults).
 *   - Sign out.
 * Delta API keys / execution mode still live on the web dashboard; this
 * screen intentionally keeps a narrow surface for phone use.
 */
export default function SettingsScreen() {
  const { user, signOut } = useAuth();
  const [rules, setRules] = useState<AlertRulesState>(DEFAULT_RULES);
  const [pushOn, setPushOn] = useState(false);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    (async () => {
      setRules(await readRules());
      setPushOn(await readPushEnabled());
    })();
  }, []);

  const togglePush = async (next: boolean) => {
    setSaving(true);
    try {
      if (next) {
        const granted = await ensureNotificationPermission();
        if (!granted) {
          Alert.alert(
            "Notifications disabled",
            "Enable notifications for Delta Terminal in your device settings to receive spread and latency alerts."
          );
          return;
        }
        await writePushEnabled(true);
        setPushOn(true);
        await registerBackgroundAlerts();
      } else {
        await writePushEnabled(false);
        setPushOn(false);
        await unregisterBackgroundAlerts();
      }
    } finally {
      setSaving(false);
    }
  };

  const updateGlobal = async (patch: Partial<AlertRulesState["global"]>) => {
    const next: AlertRulesState = { ...rules, global: { ...rules.global, ...patch } };
    setRules(next);
    await writeRules(next);
  };

  return (
    <ScrollView style={{ flex: 1, backgroundColor: colors.bg }} contentContainerStyle={{ padding: spacing.lg, paddingBottom: spacing.xxl }}>
      <Text style={styles.h1}>Settings</Text>
      {user && <Text style={styles.sub}>Signed in as {user.first_name ?? user.email}</Text>}

      <View style={styles.card}>
        <View style={styles.rowBetween}>
          <View style={{ flex: 1 }}>
            <Text style={styles.cardTitle}>Push alerts</Text>
            <Text style={styles.cardHint}>Get notified when spread or tick latency breaches your thresholds — even when the app is closed.</Text>
          </View>
          <Switch value={pushOn} disabled={saving} onValueChange={togglePush} trackColor={{ true: colors.primarySoft, false: colors.border }} thumbColor={pushOn ? colors.primary : colors.textMuted} />
        </View>

        {pushOn && (
          <TouchableOpacity style={styles.testBtn} onPress={fireTestNotification}>
            <Ionicons name="notifications-outline" size={16} color={colors.primary} />
            <Text style={styles.testBtnText}>Send test notification</Text>
          </TouchableOpacity>
        )}
      </View>

      <View style={styles.card}>
        <Text style={styles.cardTitle}>Global thresholds</Text>
        <Text style={styles.cardHint}>Per-symbol overrides can still be configured from the web dashboard.</Text>

        <ThresholdRow
          label="Spread warn (bps)"
          value={rules.global.spreadWarnBps}
          onChange={(v) => updateGlobal({ spreadWarnBps: v })}
        />
        <ThresholdRow
          label="Spread critical (bps)"
          value={rules.global.spreadCritBps}
          onChange={(v) => updateGlobal({ spreadCritBps: v })}
        />
        <ThresholdRow
          label="Latency warn (ms)"
          value={rules.global.latencyWarnMs}
          onChange={(v) => updateGlobal({ latencyWarnMs: v })}
        />
        <ThresholdRow
          label="Latency critical (ms)"
          value={rules.global.latencyCritMs}
          onChange={(v) => updateGlobal({ latencyCritMs: v })}
        />
      </View>

      <TouchableOpacity style={styles.signOut} onPress={signOut}>
        <Ionicons name="log-out-outline" size={18} color={colors.danger} />
        <Text style={styles.signOutText}>Sign out</Text>
      </TouchableOpacity>
    </ScrollView>
  );
}

function ThresholdRow({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) {
  const [txt, setTxt] = useState(String(value));
  useEffect(() => setTxt(String(value)), [value]);
  return (
    <View style={styles.thresholdRow}>
      <Text style={styles.thresholdLabel}>{label}</Text>
      <TextInput
        value={txt}
        onChangeText={setTxt}
        onEndEditing={() => {
          const n = Number(txt);
          if (Number.isFinite(n) && n > 0) onChange(n);
          else setTxt(String(value));
        }}
        keyboardType="numeric"
        style={styles.thresholdInput}
        placeholderTextColor={colors.textDim}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  h1: { color: colors.text, fontSize: 26, fontWeight: "700" },
  sub: { color: colors.textMuted, marginTop: 4, marginBottom: spacing.lg },
  card: { backgroundColor: colors.surface, borderRadius: radii.lg, borderWidth: 1, borderColor: colors.border, padding: spacing.lg, marginBottom: spacing.lg },
  cardTitle: { color: colors.text, fontSize: 16, fontWeight: "600" },
  cardHint: { color: colors.textMuted, fontSize: 12, marginTop: 4, lineHeight: 18 },
  rowBetween: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: spacing.md },
  testBtn: { flexDirection: "row", alignItems: "center", gap: spacing.sm, marginTop: spacing.md, paddingVertical: 8, paddingHorizontal: 12, borderRadius: radii.md, borderWidth: 1, borderColor: colors.border, alignSelf: "flex-start" },
  testBtnText: { color: colors.primary, fontWeight: "600" },
  thresholdRow: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", marginTop: spacing.md },
  thresholdLabel: { color: colors.textMuted, flex: 1 },
  thresholdInput: { color: colors.text, backgroundColor: colors.bgAlt, borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, paddingHorizontal: 10, paddingVertical: 6, minWidth: 100, textAlign: "right" },
  signOut: { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: spacing.sm, paddingVertical: 14, borderRadius: radii.md, borderWidth: 1, borderColor: colors.danger + "55" },
  signOutText: { color: colors.danger, fontWeight: "600" },
});
