import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useMemo } from "react";
import { Dimensions, ScrollView, StyleSheet, Text, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Stack } from "expo-router";
import { Sparkles } from "lucide-react-native";

import Colors from "@/constants/colors";
import { useDemoLedger, CATEGORY_LABELS, MOOD_OPTIONS } from "@/lib/demo-ledger";

const { width: SCREEN_WIDTH } = Dimensions.get("window");
const CARD_WIDTH = Math.min(SCREEN_WIDTH - 40, 420);

// Payment Stories - a quiet, private monthly recap. Nothing here is
// shared anywhere; it's just a friendlier way to look back at a month of
// activity than scrolling a flat transaction list.
export default function PaymentStoriesScreen() {
  const insets = useSafeAreaInsets();
  const transactions = useDemoLedger((s) => s.transactions);

  const months = useMemo(() => {
    const byMonth = new Map<string, typeof transactions>();
    transactions.forEach((t) => {
      const key = t.createdAt.toLocaleDateString("en-US", { month: "long", year: "numeric" });
      byMonth.set(key, [...(byMonth.get(key) || []), t]);
    });

    return Array.from(byMonth.entries()).map(([label, items]) => {
      const completed = items.filter((t) => t.status === "completed");
      const sent = completed.filter((t) => t.type === "send").reduce((sum, t) => sum + t.amount, 0);
      const received = completed.filter((t) => t.type === "receive").reduce((sum, t) => sum + t.amount, 0);
      const biggest = completed.reduce(
        (top, t) => (!top || t.amount > top.amount ? t : top),
        undefined as (typeof items)[number] | undefined
      );
      const moodCounts = new Map<string, number>();
      completed.forEach((t) => {
        if (t.mood) moodCounts.set(t.mood, (moodCounts.get(t.mood) || 0) + 1);
      });
      const topMood = Array.from(moodCounts.entries()).sort((a, b) => b[1] - a[1])[0];
      const momentsTagged = completed.filter((t) => !!t.category).length;

      return { label, items: completed, sent, received, biggest, topMood, momentsTagged };
    });
  }, [transactions]);

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ title: "Payment Stories", headerShown: true }} />

      {months.length === 0 ? (
        <View style={styles.emptyState}>
          <Sparkles color={Colors.dark.textTertiary} size={56} />
          <Text style={styles.emptyTitle}>Nothing to recap yet</Text>
          <Text style={styles.emptyText}>Once you've got a month of activity, it'll show up here as a story.</Text>
        </View>
      ) : (
        <ScrollView
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={scrollViewWebProps.showsHorizontalScrollIndicator}
          contentContainerStyle={styles.pager}
          snapToInterval={CARD_WIDTH + 16}
          decelerationRate="fast"
        >
          {months.map((month) => {
            const moodMeta = month.topMood ? MOOD_OPTIONS.find((m) => m.key === month.topMood![0]) : undefined;
            return (
              <View key={month.label} style={[styles.card, { width: CARD_WIDTH }]}>
                <Text style={styles.cardMonth}>{month.label}</Text>
                <Text style={styles.cardCount}>{month.items.length} payments</Text>

                <View style={styles.statsRow}>
                  <View style={styles.statBox}>
                    <Text style={styles.statValue}>${month.sent.toFixed(0)}</Text>
                    <Text style={styles.statLabel}>Sent</Text>
                  </View>
                  <View style={styles.statBox}>
                    <Text style={styles.statValue}>${month.received.toFixed(0)}</Text>
                    <Text style={styles.statLabel}>Received</Text>
                  </View>
                </View>

                {month.biggest && (
                  <View style={styles.highlightBox}>
                    <Text style={styles.highlightLabel}>Biggest moment</Text>
                    <Text style={styles.highlightText}>
                      ${month.biggest.amount.toFixed(2)} {month.biggest.type === "receive" ? "from" : "to"} {month.biggest.counterpartyName}
                    </Text>
                    {month.biggest.note && <Text style={styles.highlightNote}>"{month.biggest.note}"</Text>}
                  </View>
                )}

                {moodMeta && (
                  <View style={styles.moodBox}>
                    <Text style={styles.moodEmoji}>{moodMeta.emoji}</Text>
                    <Text style={styles.moodText}>Mostly feeling {moodMeta.label.toLowerCase()} this month</Text>
                  </View>
                )}

                <Text style={styles.tagSummary}>
                  {month.momentsTagged} payment{month.momentsTagged === 1 ? "" : "s"} auto-tagged by category
                </Text>

                <View style={styles.categoryRow}>
                  {Object.entries(CATEGORY_LABELS)
                    .filter(([key]) => month.items.some((t) => t.category === key))
                    .slice(0, 5)
                    .map(([key, meta]) => (
                      <View key={key} style={styles.categoryChip}>
                        <Text style={styles.categoryChipText}>{meta.emoji} {meta.label}</Text>
                      </View>
                    ))}
                </View>
              </View>
            );
          })}
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  emptyState: {
    flex: 1,
    alignItems: "center" as const,
    justifyContent: "center" as const,
    gap: 12,
    paddingHorizontal: 30,
  },
  emptyTitle: {
    fontSize: 17,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  emptyText: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 20,
  },
  pager: {
    paddingHorizontal: 20,
    paddingVertical: 24,
    gap: 16,
  },
  card: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 24,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 24,
    minHeight: 460,
  },
  cardMonth: {
    fontSize: 22,
    fontWeight: "800" as const,
    color: Colors.dark.text,
  },
  cardCount: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    marginTop: 2,
    marginBottom: 20,
  },
  statsRow: {
    flexDirection: "row" as const,
    gap: 12,
    marginBottom: 20,
  },
  statBox: {
    flex: 1,
    backgroundColor: Colors.dark.surfaceElevated,
    borderRadius: 14,
    paddingVertical: 16,
    alignItems: "center" as const,
  },
  statValue: {
    fontSize: 22,
    fontWeight: "800" as const,
    color: Colors.dark.text,
  },
  statLabel: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  highlightBox: {
    backgroundColor: `${Colors.dark.primary}0F`,
    borderRadius: 14,
    padding: 16,
    marginBottom: 16,
  },
  highlightLabel: {
    fontSize: 11,
    fontWeight: "700" as const,
    color: Colors.dark.primary,
    textTransform: "uppercase" as const,
    letterSpacing: 0.5,
    marginBottom: 6,
  },
  highlightText: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  highlightNote: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    marginTop: 4,
  },
  moodBox: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 10,
    marginBottom: 16,
  },
  moodEmoji: {
    fontSize: 24,
  },
  moodText: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    flex: 1,
  },
  tagSummary: {
    fontSize: 12,
    color: Colors.dark.textTertiary,
    marginBottom: 10,
  },
  categoryRow: {
    flexDirection: "row" as const,
    flexWrap: "wrap" as const,
    gap: 8,
  },
  categoryChip: {
    backgroundColor: Colors.dark.surfaceElevated,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderRadius: 10,
  },
  categoryChipText: {
    fontSize: 12,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
});
