import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
  Switch,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useRouter, Stack } from "expo-router";
import {
  ChevronLeft,
  ShieldAlert,
  Smartphone,
  AlertTriangle,
  CheckCircle2,
  Info,
  ShieldCheck,
} from "lucide-react-native";
import Colors from "@/constants/colors";
import { useAuth } from "@/lib/auth-context";
import { trpc } from "@/lib/trpc";
import { showAlert } from "@/lib/utils/alert";

function colorForSeverity(severity: string) {
  if (severity === "high") return "#EF4444";
  if (severity === "medium") return "#F59E0B";
  return "#6366F1";
}

export default function RiskMonitorScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { isDemoMode } = useAuth();
  const [toggling, setToggling] = useState(false);

  const overviewQuery = trpc.risk.myOverview.useQuery(undefined, { enabled: !isDemoMode });
  const utils = trpc.useUtils();
  const protectionMutation = trpc.risk.setEnhancedProtection.useMutation({
    onSuccess: (result) => {
      showAlert(result.enabled ? "Enhanced Protection on" : "Enhanced Protection off", result.message);
      utils.risk.myOverview.invalidate();
    },
    onError: (err) => showAlert("Couldn't update", err.message),
    onSettled: () => setToggling(false),
  });

  const data = overviewQuery.data;
  const levelColor = data ? colorForSeverity(data.level) : Colors.dark.textTertiary;

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ headerShown: false }} />
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backBtn}>
          <ChevronLeft size={22} color={Colors.dark.text} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Zendo AI Risk Monitor</Text>
        <View style={{ width: 36 }} />
      </View>

      {isDemoMode ? (
        <View style={styles.emptyState}>
          <ShieldAlert size={48} color={Colors.dark.textTertiary} />
          <Text style={styles.emptyText}>Risk monitoring needs a real account.</Text>
        </View>
      ) : overviewQuery.isLoading ? (
        <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 60 }} />
      ) : !data ? (
        <View style={styles.emptyState}>
          <Text style={styles.emptyText}>Couldn&apos;t load your risk overview.</Text>
        </View>
      ) : (
        <ScrollView
          style={styles.scroll}
          contentContainerStyle={[styles.scrollContent, { paddingBottom: insets.bottom + 32 }]}
          showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}
        >
          <View style={[styles.heroCard, { backgroundColor: levelColor }]}>
            <ShieldAlert size={28} color="#fff" />
            <Text style={styles.heroValue}>{data.riskScore}</Text>
            <Text style={styles.heroLabel}>
              {data.level === "low" ? "Low risk" : data.level === "medium" ? "Medium risk" : "High risk"} right now
            </Text>
          </View>

          <View style={styles.protectionCard}>
            <View style={styles.protectionLeft}>
              <ShieldCheck size={20} color={Colors.dark.primary} />
              <View style={{ flex: 1 }}>
                <Text style={styles.protectionTitle}>Enhanced Protection</Text>
                <Text style={styles.protectionSub}>Tighten transfer limits and flag new devices/recipients more aggressively.</Text>
              </View>
            </View>
            <Switch
              value={data.enhancedProtectionEnabled}
              disabled={toggling}
              onValueChange={(value) => {
                setToggling(true);
                protectionMutation.mutate({ enabled: value });
              }}
              trackColor={{ false: Colors.dark.border, true: `${Colors.dark.primary}80` }}
              thumbColor={data.enhancedProtectionEnabled ? Colors.dark.primary : "#f4f3f4"}
            />
          </View>

          <Text style={styles.sectionTitle}>Active signals</Text>
          {data.signals.length === 0 ? (
            <View style={styles.cleanCard}>
              <CheckCircle2 size={20} color="#10B981" />
              <Text style={styles.cleanText}>Nothing unusual detected - you&apos;re all clear.</Text>
            </View>
          ) : (
            data.signals.map((signal, i) => {
              const color = colorForSeverity(signal.severity);
              return (
                <View key={i} style={[styles.signalCard, { backgroundColor: `${color}10` }]}>
                  <AlertTriangle size={18} color={color} />
                  <View style={{ flex: 1 }}>
                    <Text style={[styles.signalLabel, { color }]}>{signal.label}</Text>
                    <Text style={styles.signalDetail}>{signal.detail}</Text>
                  </View>
                </View>
              );
            })
          )}

          {data.devices.length > 0 && (
            <>
              <Text style={styles.sectionTitle}>Devices</Text>
              {data.devices.map((d) => (
                <View key={d.id} style={styles.deviceRow}>
                  <Smartphone size={18} color={Colors.dark.textSecondary} />
                  <View style={{ flex: 1 }}>
                    <Text style={styles.deviceLabel}>{d.deviceType} · {d.os}</Text>
                    <Text style={styles.deviceMeta}>
                      Last seen {new Date(d.lastSeenAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                    </Text>
                  </View>
                  <Text style={[styles.trustBadge, { color: d.trustLevel === "trusted" || d.trustLevel === "high" ? "#10B981" : Colors.dark.textTertiary }]}>
                    {d.trustLevel}
                  </Text>
                </View>
              ))}
            </>
          )}

          <View style={styles.statsRow}>
            <View style={styles.statBox}>
              <Text style={styles.statValue}>{data.openAlertCount}</Text>
              <Text style={styles.statLabel}>Open alerts</Text>
            </View>
            <View style={styles.statBox}>
              <Text style={styles.statValue}>{data.velocityRuleCount}</Text>
              <Text style={styles.statLabel}>Active velocity rules</Text>
            </View>
          </View>

          <View style={styles.demoBanner}>
            <Info size={14} color={Colors.dark.primary} />
            <Text style={styles.demoBannerText}>
              Signals come from Zendo&apos;s own fraud-prevention layer (device fingerprinting, behavioral baseline, SIM-swap and velocity checks) - nothing here is shared outside the app.
            </Text>
          </View>
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.dark.background },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingVertical: 14,
    borderBottomWidth: 1,
    borderBottomColor: Colors.dark.border,
  },
  backBtn: { width: 36, height: 36, borderRadius: 18, backgroundColor: Colors.dark.surface, alignItems: "center", justifyContent: "center" },
  headerTitle: { fontSize: 16, fontWeight: "700", color: Colors.dark.text },
  scroll: { flex: 1 },
  scrollContent: { padding: 20, gap: 14 },
  emptyState: { flex: 1, alignItems: "center", justifyContent: "center", padding: 40, gap: 12 },
  emptyText: { fontSize: 14, color: Colors.dark.textSecondary, textAlign: "center" },
  heroCard: { borderRadius: 20, padding: 24, alignItems: "center", gap: 6 },
  heroValue: { fontSize: 40, fontWeight: "800", color: "#fff" },
  heroLabel: { fontSize: 13, color: "rgba(255,255,255,0.85)", fontWeight: "600" },
  protectionCard: {
    flexDirection: "row",
    alignItems: "center",
    gap: 12,
    backgroundColor: Colors.dark.surface,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
  },
  protectionLeft: { flexDirection: "row", alignItems: "center", gap: 12, flex: 1 },
  protectionTitle: { fontSize: 14, fontWeight: "700", color: Colors.dark.text },
  protectionSub: { fontSize: 12, color: Colors.dark.textSecondary, marginTop: 2, lineHeight: 16 },
  sectionTitle: { fontSize: 15, fontWeight: "700", color: Colors.dark.text, marginTop: 8 },
  cleanCard: {
    flexDirection: "row",
    alignItems: "center",
    gap: 10,
    backgroundColor: "#F0FDF4",
    borderRadius: 14,
    padding: 16,
  },
  cleanText: { fontSize: 13, color: "#10B981", fontWeight: "600", flex: 1 },
  signalCard: { flexDirection: "row", gap: 10, borderRadius: 14, padding: 14, alignItems: "flex-start" },
  signalLabel: { fontSize: 13, fontWeight: "700" },
  signalDetail: { fontSize: 12, color: Colors.dark.textSecondary, marginTop: 2, lineHeight: 16 },
  deviceRow: {
    flexDirection: "row",
    alignItems: "center",
    gap: 10,
    backgroundColor: Colors.dark.surface,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 12,
  },
  deviceLabel: { fontSize: 13, fontWeight: "600", color: Colors.dark.text, textTransform: "capitalize" },
  deviceMeta: { fontSize: 11, color: Colors.dark.textTertiary, marginTop: 2 },
  trustBadge: { fontSize: 11, fontWeight: "700", textTransform: "uppercase" },
  statsRow: { flexDirection: "row", gap: 12, marginTop: 8 },
  statBox: {
    flex: 1,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
    alignItems: "center",
  },
  statValue: { fontSize: 20, fontWeight: "700", color: Colors.dark.text },
  statLabel: { fontSize: 11, color: Colors.dark.textSecondary, marginTop: 4, textAlign: "center" },
  demoBanner: { flexDirection: "row", gap: 8, backgroundColor: `${Colors.dark.primary}10`, borderRadius: 12, padding: 14, marginTop: 8 },
  demoBannerText: { fontSize: 11, color: Colors.dark.primary, flex: 1, lineHeight: 16 },
});
