import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useMemo, useState } from "react";
import { Modal, Pressable, ScrollView, Share, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Stack } from "expo-router";
import { Receipt as ReceiptIcon, Share2, X } from "lucide-react-native";

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

// Auto-Organized Receipts - every "merchant" transaction in the ledger
// quietly generates one of these the moment it completes (see merchantPay
// in lib/demo-ledger.ts). This screen is just the filing cabinet for them
// so they're never buried back in the regular activity feed.
export default function ReceiptsScreen() {
  const insets = useSafeAreaInsets();
  const receipts = useDemoLedger((s) => s.receipts);
  const [selected, setSelected] = useState<DemoReceipt | null>(null);

  const grouped = useMemo(() => {
    const byMonth = new Map<string, DemoReceipt[]>();
    receipts.forEach((r) => {
      const key = r.createdAt.toLocaleDateString("en-US", { month: "long", year: "numeric" });
      byMonth.set(key, [...(byMonth.get(key) || []), r]);
    });
    return Array.from(byMonth.entries());
  }, [receipts]);

  const handleShare = async (receipt: DemoReceipt) => {
    try {
      await Share.share({
        message: `Receipt - ${receipt.merchantName}: $${receipt.amount.toFixed(2)} on ${receipt.createdAt.toLocaleDateString()}`,
      });
    } catch {
      // Share sheet can be dismissed without choosing a destination.
    }
  };

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

      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
        {receipts.length === 0 ? (
          <View style={styles.emptyState}>
            <ReceiptIcon color={Colors.dark.textTertiary} size={56} />
            <Text style={styles.emptyTitle}>No receipts yet</Text>
            <Text style={styles.emptyText}>
              Pay a business through Zendo and a clean, itemized receipt will land here automatically.
            </Text>
          </View>
        ) : (
          grouped.map(([month, items]) => (
            <View key={month} style={styles.monthGroup}>
              <Text style={styles.monthLabel}>{month}</Text>
              {items.map((receipt) => {
                const meta = receipt.category ? CATEGORY_LABELS[receipt.category] : undefined;
                return (
                  <TouchableOpacity
                    key={receipt.id}
                    style={styles.receiptRow}
                    activeOpacity={0.7}
                    onPress={() => setSelected(receipt)}
                  >
                    <View style={styles.receiptIcon}>
                      <Text style={styles.receiptIconText}>{meta?.emoji || "🧾"}</Text>
                    </View>
                    <View style={styles.receiptInfo}>
                      <Text style={styles.merchantName}>{receipt.merchantName}</Text>
                      <Text style={styles.receiptMeta}>
                        {meta?.label || "General"} · {receipt.createdAt.toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                      </Text>
                    </View>
                    <Text style={styles.amount}>${receipt.amount.toFixed(2)}</Text>
                  </TouchableOpacity>
                );
              })}
            </View>
          ))
        )}
      </ScrollView>

      <Modal visible={!!selected} transparent animationType="fade" onRequestClose={() => setSelected(null)}>
        <Pressable style={styles.backdrop} onPress={() => setSelected(null)}>
          <Pressable style={styles.detailCard} onPress={(e) => e.stopPropagation()}>
            <View style={styles.detailHeader}>
              <Text style={styles.detailTitle}>Receipt</Text>
              <TouchableOpacity onPress={() => setSelected(null)} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                <X color={Colors.dark.textSecondary} size={20} />
              </TouchableOpacity>
            </View>
            {selected && (
              <>
                <Text style={styles.detailMerchant}>{selected.merchantName}</Text>
                <Text style={styles.detailAmount}>${selected.amount.toFixed(2)}</Text>
                <View style={styles.detailDivider} />
                <View style={styles.detailRow}>
                  <Text style={styles.detailLabel}>Date</Text>
                  <Text style={styles.detailValue}>
                    {selected.createdAt.toLocaleString("en-US", { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" })}
                  </Text>
                </View>
                <View style={styles.detailRow}>
                  <Text style={styles.detailLabel}>Category</Text>
                  <Text style={styles.detailValue}>
                    {selected.category ? CATEGORY_LABELS[selected.category].label : "General"}
                  </Text>
                </View>
                <View style={styles.detailRow}>
                  <Text style={styles.detailLabel}>Receipt ID</Text>
                  <Text style={styles.detailValueMono}>{selected.id}</Text>
                </View>
                <TouchableOpacity style={styles.shareButton} onPress={() => handleShare(selected)} activeOpacity={0.85}>
                  <Share2 color="#FFFFFF" size={16} />
                  <Text style={styles.shareButtonText}>Share Receipt</Text>
                </TouchableOpacity>
              </>
            )}
          </Pressable>
        </Pressable>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  content: {
    padding: 20,
    paddingBottom: 60,
  },
  emptyState: {
    alignItems: "center" as const,
    paddingTop: 80,
    gap: 12,
    paddingHorizontal: 20,
  },
  emptyTitle: {
    fontSize: 17,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  emptyText: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 20,
  },
  monthGroup: {
    marginBottom: 24,
  },
  monthLabel: {
    fontSize: 13,
    fontWeight: "700" as const,
    color: Colors.dark.textSecondary,
    textTransform: "uppercase" as const,
    letterSpacing: 0.5,
    marginBottom: 10,
  },
  receiptRow: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 12,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
    marginBottom: 10,
  },
  receiptIcon: {
    width: 42,
    height: 42,
    borderRadius: 12,
    backgroundColor: Colors.dark.surfaceElevated,
    alignItems: "center" as const,
    justifyContent: "center" as const,
  },
  receiptIconText: {
    fontSize: 20,
  },
  receiptInfo: {
    flex: 1,
  },
  merchantName: {
    fontSize: 15,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  receiptMeta: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  amount: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  backdrop: {
    flex: 1,
    backgroundColor: "rgba(0,0,0,0.5)",
    justifyContent: "center" as const,
    padding: 20,
  },
  detailCard: {
    backgroundColor: Colors.dark.background,
    borderRadius: 20,
    padding: 24,
  },
  detailHeader: {
    flexDirection: "row" as const,
    justifyContent: "space-between",
    alignItems: "center" as const,
    marginBottom: 16,
  },
  detailTitle: {
    fontSize: 13,
    fontWeight: "700" as const,
    color: Colors.dark.textSecondary,
    textTransform: "uppercase" as const,
    letterSpacing: 0.5,
  },
  detailMerchant: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  detailAmount: {
    fontSize: 32,
    fontWeight: "800" as const,
    color: Colors.dark.primary,
    marginTop: 4,
    marginBottom: 16,
  },
  detailDivider: {
    height: 1,
    backgroundColor: Colors.dark.border,
    marginBottom: 16,
  },
  detailRow: {
    flexDirection: "row" as const,
    justifyContent: "space-between",
    marginBottom: 12,
  },
  detailLabel: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
  },
  detailValue: {
    fontSize: 13,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  detailValueMono: {
    fontSize: 12,
    fontFamily: "monospace",
    color: Colors.dark.textSecondary,
  },
  shareButton: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    justifyContent: "center" as const,
    gap: 8,
    backgroundColor: Colors.dark.primary,
    paddingVertical: 14,
    borderRadius: 12,
    marginTop: 8,
  },
  shareButtonText: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: "#FFFFFF",
  },
});
