import { useMemo } from "react";
import { Image, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { Sparkles } from "lucide-react-native";

import Colors from "@/constants/colors";
import { useDemoLedger } from "@/lib/demo-ledger";
import { hapticSelection } from "@/lib/ui/haptics";

export interface SplitSuggestion {
  name: string;
  avatar?: string;
  shareOfSplits: number;
}

interface SmartSplitBubbleProps {
  onApply: (people: SplitSuggestion[]) => void;
  style?: object;
}

// Smart Split Bubble - looks at who you've split money with most in the
// past (anyone tagged with a note that smells like a group expense, or
// who you've just sent money to a lot) and floats a one-tap suggestion
// instead of making you pick names from scratch every time.
const GROUP_KEYWORDS = ["split", "dinner", "rent", "trip", "tickets", "group"];

export function SmartSplitBubble({ onApply, style }: SmartSplitBubbleProps) {
  const transactions = useDemoLedger((s) => s.transactions);

  const suggestion = useMemo(() => {
    const counts = new Map<string, { count: number; avatar?: string }>();

    transactions.forEach((t) => {
      if (t.type !== "send" && t.type !== "receive") return;
      const looksLikeGroupSpend = t.note
        ? GROUP_KEYWORDS.some((kw) => t.note!.toLowerCase().includes(kw))
        : false;
      const weight = looksLikeGroupSpend ? 2 : 1;
      const existing = counts.get(t.counterpartyName);
      counts.set(t.counterpartyName, {
        count: (existing?.count || 0) + weight,
        avatar: existing?.avatar || t.counterpartyAvatar,
      });
    });

    const ranked = Array.from(counts.entries())
      .map(([name, v]) => ({ name, avatar: v.avatar, shareOfSplits: v.count }))
      .sort((a, b) => b.shareOfSplits - a.shareOfSplits)
      .slice(0, 2);

    return ranked.length >= 1 ? ranked : null;
  }, [transactions]);

  if (!suggestion) return null;

  const names = suggestion.map((s) => s.name).join(" and ");

  return (
    <TouchableOpacity
      style={[styles.bubble, style]}
      activeOpacity={0.85}
      onPress={() => {
        hapticSelection();
        onApply(suggestion);
      }}
    >
      <View style={styles.iconWrap}>
        <Sparkles color={Colors.dark.primary} size={18} />
      </View>
      <View style={styles.textWrap}>
        <Text style={styles.title}>Split with {names}?</Text>
        <Text style={styles.subtitle}>Based on who you usually split costs with</Text>
      </View>
      <View style={styles.avatarStack}>
        {suggestion.map((person) => (
          <Image
            key={person.name}
            source={{ uri: person.avatar || `https://i.pravatar.cc/150?u=${person.name}` }}
            style={styles.avatar}
          />
        ))}
      </View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  bubble: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 12,
    backgroundColor: `${Colors.dark.primary}0F`,
    borderWidth: 1,
    borderColor: `${Colors.dark.primary}30`,
    borderRadius: 16,
    padding: 14,
    marginHorizontal: 20,
    marginBottom: 16,
  },
  iconWrap: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: `${Colors.dark.primary}1A`,
    alignItems: "center" as const,
    justifyContent: "center" as const,
  },
  textWrap: {
    flex: 1,
  },
  title: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  subtitle: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  avatarStack: {
    flexDirection: "row" as const,
  },
  avatar: {
    width: 28,
    height: 28,
    borderRadius: 14,
    marginLeft: -10,
    borderWidth: 2,
    borderColor: Colors.dark.background,
    backgroundColor: Colors.dark.surfaceElevated,
  },
});
