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

const NODE_ICONS: Record<string, typeof Fingerprint> = {
  verification: CheckCircle2,
  device: Smartphone,
  behavior: Brain,
  network: Users,
  history: History,
  risk: ShieldAlert,
};

function colorForStatus(status: string) {
  if (status === "strong") return "#10B981";
  if (status === "developing") return "#F59E0B";
  if (status === "attention") return "#EF4444";
  return Colors.dark.textTertiary; // no_data
}

export default function IdentityGraphScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { isDemoMode } = useAuth();

  const graphQuery = trpc.identity.graph.useQuery(undefined, { enabled: !isDemoMode });
  const data = graphQuery.data;

  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}>Identity Graph</Text>
        <View style={{ width: 36 }} />
      </View>

      {isDemoMode ? (
        <View style={styles.emptyState}>
          <Fingerprint size={48} color={Colors.dark.textTertiary} />
          <Text style={styles.emptyText}>The Identity Graph needs a real account to synthesize signals from.</Text>
        </View>
      ) : graphQuery.isLoading ? (
        <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 60 }} />
      ) : !data ? (
        <View style={styles.emptyState}>
          <Text style={styles.emptyText}>Couldn&apos;t load your Identity Graph.</Text>
        </View>
      ) : (
        <ScrollView
          style={styles.scroll}
          contentContainerStyle={[styles.scrollContent, { paddingBottom: insets.bottom + 32 }]}
          showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}
        >
          <View style={styles.heroCard}>
            <View style={styles.heroTop}>
              <View style={styles.heroIcon}>
                <Fingerprint size={28} color="#fff" />
              </View>
              <View style={styles.heroMeta}>
                <Text style={styles.heroTitle}>Zendo Financial Identity Graph</Text>
                <Text style={styles.heroSub}>Your account&apos;s fraud-resistance signal</Text>
              </View>
            </View>
            <Text style={styles.scoreValue}>{data.overall}</Text>
            <Text style={[styles.scoreStatus, { color: colorForStatus(data.overallStatus) }]}>
              {data.overallStatus === "strong" ? "Strong" : data.overallStatus === "developing" ? "Developing" : "Needs attention"}
            </Text>
            <Text style={styles.accountAge}>Account age: {data.accountAgeDays} day{data.accountAgeDays === 1 ? "" : "s"}</Text>
          </View>

          {/* Graph visualization */}
          <View style={styles.graphCard}>
            <View style={styles.graphCenter}>
              <ShieldCheck size={22} color="#fff" />
              <Text style={styles.graphCenterText}>You</Text>
            </View>
            <View style={styles.graphNodesGrid}>
              {data.nodes.map((node) => {
                const Icon = NODE_ICONS[node.category] ?? Info;
                const color = colorForStatus(node.status);
                return (
                  <View key={node.id} style={styles.graphNode}>
                    <View
                      style={[
                        styles.graphNodeLine,
                        { backgroundColor: color, opacity: 0.25 + node.linkStrength * 0.6 },
                      ]}
                    />
                    <View style={[styles.graphNodeCircle, { borderColor: color }]}>
                      <Icon size={16} color={color} />
                    </View>
                    <Text style={styles.graphNodeLabel}>{node.label}</Text>
                    <Text style={[styles.graphNodeScore, { color }]}>{Math.round(node.score)}</Text>
                  </View>
                );
              })}
            </View>
          </View>

          <Text style={styles.sectionTitle}>What each signal means</Text>
          {data.nodes.map((node) => {
            const Icon = NODE_ICONS[node.category] ?? Info;
            const color = colorForStatus(node.status);
            const StatusIcon = node.status === "strong" ? CheckCircle2 : node.status === "attention" ? AlertTriangle : Info;
            return (
              <View key={node.id} style={styles.detailCard}>
                <View style={[styles.detailIcon, { backgroundColor: `${color}20` }]}>
                  <Icon size={18} color={color} />
                </View>
                <View style={styles.detailBody}>
                  <View style={styles.detailTitleRow}>
                    <Text style={styles.detailTitle}>{node.label}</Text>
                    <StatusIcon size={14} color={color} />
                  </View>
                  <Text style={styles.detailText}>{node.detail}</Text>
                </View>
              </View>
            );
          })}

          <View style={styles.demoBanner}>
            <Text style={styles.demoBannerText}>{data.disclaimer}</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: 17, 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: {
    backgroundColor: Colors.dark.primary,
    borderRadius: 20,
    padding: 22,
    alignItems: "center",
    gap: 6,
  },
  heroTop: { flexDirection: "row", alignItems: "center", gap: 14, alignSelf: "stretch", marginBottom: 8 },
  heroIcon: { width: 52, height: 52, borderRadius: 16, backgroundColor: "rgba(255,255,255,0.15)", alignItems: "center", justifyContent: "center" },
  heroMeta: { flex: 1 },
  heroTitle: { fontSize: 16, fontWeight: "700", color: "#fff" },
  heroSub: { fontSize: 12, color: "rgba(255,255,255,0.65)", marginTop: 2 },
  scoreValue: { fontSize: 44, fontWeight: "800", color: "#fff" },
  scoreStatus: { fontSize: 14, fontWeight: "700" },
  accountAge: { fontSize: 12, color: "rgba(255,255,255,0.6)", marginTop: 4 },
  graphCard: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 18,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 20,
    alignItems: "center",
    gap: 16,
  },
  graphCenter: {
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: Colors.dark.primary,
    alignItems: "center",
    justifyContent: "center",
    gap: 2,
  },
  graphCenterText: { fontSize: 10, fontWeight: "700", color: "#fff" },
  graphNodesGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "center",
    gap: 16,
  },
  graphNode: { alignItems: "center", width: 80, gap: 4 },
  graphNodeLine: { width: 2, height: 14, borderRadius: 1 },
  graphNodeCircle: {
    width: 40,
    height: 40,
    borderRadius: 20,
    borderWidth: 2,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: Colors.dark.surfaceElevated,
  },
  graphNodeLabel: { fontSize: 10, color: Colors.dark.textSecondary, textAlign: "center" },
  graphNodeScore: { fontSize: 12, fontWeight: "800" },
  sectionTitle: { fontSize: 15, fontWeight: "700", color: Colors.dark.text, marginTop: 8 },
  detailCard: {
    flexDirection: "row",
    gap: 12,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
  },
  detailIcon: { width: 36, height: 36, borderRadius: 10, alignItems: "center", justifyContent: "center", flexShrink: 0 },
  detailBody: { flex: 1, gap: 4 },
  detailTitleRow: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
  detailTitle: { fontSize: 14, fontWeight: "700", color: Colors.dark.text },
  detailText: { fontSize: 12, color: Colors.dark.textSecondary, lineHeight: 17 },
  demoBanner: { backgroundColor: `${Colors.dark.primary}10`, borderRadius: 12, padding: 14, marginTop: 8 },
  demoBannerText: { fontSize: 12, color: Colors.dark.primary, textAlign: "center", fontWeight: "500" },
});
