import { useMemo } from "react";
import { Image, Modal, Pressable, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { Shield, ShieldCheck, X } from "lucide-react-native";

import Colors from "@/constants/colors";
import { useDemoLedger } from "@/lib/demo-ledger";
import { useTrustedCircle } from "@/lib/social/trusted-circle";
import { hapticSelection, hapticToggle } from "@/lib/ui/haptics";

export interface MiniProfilePerson {
  name: string;
  username?: string;
  avatar?: string;
}

interface MiniProfileSheetProps {
  visible: boolean;
  person: MiniProfilePerson | null;
  onClose: () => void;
  onSend?: () => void;
}

// Mini-Profiles - tap a name almost anywhere people show up (friends,
// contacts, a transaction) and get the condensed version of "who is this
// to me": how much history you two have, when you last interacted, and a
// rough trust score. The score is a simple heuristic, not a credit check - it's meant to be reassuring at a glance, not authoritative.
export function MiniProfileSheet({ visible, person, onClose, onSend }: MiniProfileSheetProps) {
  const transactions = useDemoLedger((s) => s.transactions);
  const isTrusted = useTrustedCircle((s) => s.isTrusted(person?.username));
  const toggleTrusted = useTrustedCircle((s) => s.toggleTrusted);

  const stats = useMemo(() => {
    if (!person) return null;
    const shared = transactions.filter((t) => t.counterpartyName === person.name);
    const completed = shared.filter((t) => t.status === "completed");
    const sentToThem = completed
      .filter((t) => t.type === "send" || t.type === "request")
      .reduce((sum, t) => (t.type === "send" ? sum + t.amount : sum), 0);
    const receivedFromThem = completed
      .filter((t) => t.type === "receive")
      .reduce((sum, t) => sum + t.amount, 0);
    const last = shared.length > 0
      ? shared.reduce((latest, t) => (t.createdAt > latest ? t.createdAt : latest), shared[0].createdAt)
      : undefined;

    const score = Math.min(99, Math.max(35, 40 + completed.length * 8 + (isTrusted ? 15 : 0)));

    return {
      count: shared.length,
      sentToThem,
      receivedFromThem,
      last,
      score,
    };
  }, [transactions, person, isTrusted]);

  if (!person) return null;

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
      <Pressable style={styles.backdrop} onPress={onClose}>
        <Pressable style={styles.sheet} onPress={(e) => e.stopPropagation()}>
          <View style={styles.header}>
            <TouchableOpacity onPress={onClose} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
              <X color={Colors.dark.textSecondary} size={20} />
            </TouchableOpacity>
          </View>

          <View style={styles.identity}>
            <Image
              source={{ uri: person.avatar || `https://i.pravatar.cc/150?u=${person.name}` }}
              style={styles.avatar}
            />
            <Text style={styles.name}>{person.name}</Text>
            {person.username && <Text style={styles.username}>@{person.username}</Text>}
          </View>

          <View style={styles.scoreCard}>
            <View style={styles.scoreRow}>
              {isTrusted ? (
                <ShieldCheck color={Colors.dark.success} size={18} />
              ) : (
                <Shield color={Colors.dark.textSecondary} size={18} />
              )}
              <Text style={styles.scoreLabel}>Trust score</Text>
              <Text style={styles.scoreValue}>{stats?.score ?? 40}</Text>
            </View>
            <View style={styles.scoreTrack}>
              <View style={[styles.scoreFill, { width: `${stats?.score ?? 40}%` }]} />
            </View>
          </View>

          <View style={styles.statsRow}>
            <View style={styles.statBox}>
              <Text style={styles.statValue}>{stats?.count ?? 0}</Text>
              <Text style={styles.statLabel}>Shared payments</Text>
            </View>
            <View style={styles.statBox}>
              <Text style={styles.statValue}>${(stats?.sentToThem ?? 0).toFixed(0)}</Text>
              <Text style={styles.statLabel}>You've sent</Text>
            </View>
            <View style={styles.statBox}>
              <Text style={styles.statValue}>${(stats?.receivedFromThem ?? 0).toFixed(0)}</Text>
              <Text style={styles.statLabel}>You've received</Text>
            </View>
          </View>

          <Text style={styles.lastInteraction}>
            {stats?.last
              ? `Last interaction ${stats.last.toLocaleDateString("en-US", { month: "short", day: "numeric" })}`
              : "No shared history yet"}
          </Text>

          <View style={styles.actions}>
            {person.username && (
              <TouchableOpacity
                style={[styles.trustButton, isTrusted && styles.trustButtonActive]}
                onPress={() => {
                  hapticToggle();
                  toggleTrusted(person.username!);
                }}
                activeOpacity={0.85}
              >
                {isTrusted ? (
                  <ShieldCheck color={Colors.dark.success} size={16} />
                ) : (
                  <Shield color={Colors.dark.text} size={16} />
                )}
                <Text style={[styles.trustButtonText, isTrusted && styles.trustButtonTextActive]}>
                  {isTrusted ? "In Trusted Circle" : "Add to Trusted Circle"}
                </Text>
              </TouchableOpacity>
            )}
            {onSend && (
              <TouchableOpacity
                style={styles.sendButton}
                onPress={() => {
                  hapticSelection();
                  onSend();
                }}
                activeOpacity={0.85}
              >
                <Text style={styles.sendButtonText}>Send Money</Text>
              </TouchableOpacity>
            )}
          </View>
        </Pressable>
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  backdrop: {
    flex: 1,
    backgroundColor: "rgba(0,0,0,0.5)",
    justifyContent: "flex-end" as const,
  },
  sheet: {
    backgroundColor: Colors.dark.background,
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    padding: 24,
    paddingBottom: 36,
  },
  header: {
    alignItems: "flex-end" as const,
  },
  identity: {
    alignItems: "center" as const,
    marginTop: 4,
    marginBottom: 20,
  },
  avatar: {
    width: 76,
    height: 76,
    borderRadius: 38,
    backgroundColor: Colors.dark.surfaceElevated,
    marginBottom: 10,
  },
  name: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  username: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  scoreCard: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
    marginBottom: 16,
  },
  scoreRow: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 8,
    marginBottom: 8,
  },
  scoreLabel: {
    flex: 1,
    fontSize: 13,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  scoreValue: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.primary,
  },
  scoreTrack: {
    height: 6,
    borderRadius: 3,
    backgroundColor: Colors.dark.surfaceElevated,
    overflow: "hidden",
  },
  scoreFill: {
    height: 6,
    borderRadius: 3,
    backgroundColor: Colors.dark.primary,
  },
  statsRow: {
    flexDirection: "row" as const,
    gap: 10,
    marginBottom: 14,
  },
  statBox: {
    flex: 1,
    backgroundColor: Colors.dark.surface,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    paddingVertical: 12,
    alignItems: "center" as const,
  },
  statValue: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  statLabel: {
    fontSize: 11,
    color: Colors.dark.textSecondary,
    marginTop: 2,
    textAlign: "center" as const,
  },
  lastInteraction: {
    fontSize: 12,
    color: Colors.dark.textTertiary,
    textAlign: "center" as const,
    marginBottom: 18,
  },
  actions: {
    gap: 10,
  },
  trustButton: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    justifyContent: "center" as const,
    gap: 8,
    paddingVertical: 14,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    backgroundColor: Colors.dark.surface,
  },
  trustButtonActive: {
    borderColor: Colors.dark.success,
    backgroundColor: `${Colors.dark.success}14`,
  },
  trustButtonText: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  trustButtonTextActive: {
    color: Colors.dark.success,
  },
  sendButton: {
    backgroundColor: Colors.dark.primary,
    paddingVertical: 16,
    borderRadius: 14,
    alignItems: "center" as const,
  },
  sendButtonText: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: "#FFFFFF",
  },
});
