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

import Colors from "@/constants/colors";
import { useAuth } from "@/lib/auth-context";
import { trpc } from "@/lib/trpc";

const CATEGORY_COLORS: Record<string, string> = {
  Dining: "#F59E0B",
  Groceries: "#10B981",
  Travel: "#3B82F6",
  Transport: "#8B5CF6",
  General: Colors.dark.primary,
};

export default function RewardsScreen() {
  const insets = useSafeAreaInsets();
  const { isDemoMode } = useAuth();

  const rewardsQuery = trpc.rewards.get.useQuery(undefined, { enabled: !isDemoMode });

  const totalEarned = isDemoMode ? 18.42 : rewardsQuery.data?.totalEarned ?? 0;
  const categories = isDemoMode
    ? [
        { category: "Dining", spend: 210, cashback: 8.4 },
        { category: "Groceries", spend: 180, cashback: 5.4 },
        { category: "General", spend: 462, cashback: 4.62 },
      ]
    : rewardsQuery.data?.categories ?? [];
  const recent = isDemoMode ? [] : rewardsQuery.data?.recent ?? [];

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

      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
        <View style={styles.heroCard}>
          <Gift color={Colors.dark.primary} size={28} />
          <Text style={styles.heroValue}>${totalEarned.toFixed(2)}</Text>
          <Text style={styles.heroLabel}>Total cashback earned</Text>
        </View>

        {isDemoMode && (
          <View style={styles.demoNotice}>
            <Text style={styles.demoNoticeText}>
              Demo Mode - showing sample rewards. Real cashback is earned on card purchases at merchants.
            </Text>
          </View>
        )}

        <Text style={styles.sectionTitle}>By category</Text>

        {!isDemoMode && rewardsQuery.isLoading ? (
          <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 20 }} />
        ) : categories.length === 0 ? (
          <View style={styles.emptyState}>
            <TrendingUp color={Colors.dark.textTertiary} size={40} />
            <Text style={styles.emptyText}>
              No cashback yet. Pay with your Zendo card at a merchant to start earning.
            </Text>
          </View>
        ) : (
          <View style={styles.categoryList}>
            {categories.map((c) => (
              <View key={c.category} style={styles.categoryRow}>
                <View
                  style={[
                    styles.categoryDot,
                    { backgroundColor: CATEGORY_COLORS[c.category] || Colors.dark.primary },
                  ]}
                />
                <View style={styles.categoryInfo}>
                  <Text style={styles.categoryName}>{c.category}</Text>
                  <Text style={styles.categorySpend}>${c.spend.toFixed(2)} spent</Text>
                </View>
                <Text style={styles.categoryCashback}>+${c.cashback.toFixed(2)}</Text>
              </View>
            ))}
          </View>
        )}

        {!isDemoMode && recent.length > 0 && (
          <>
            <Text style={styles.sectionTitle}>Recent cashback</Text>
            <View style={styles.categoryList}>
              {recent.map((entry) => (
                <View key={entry.id} style={styles.categoryRow}>
                  <View
                    style={[
                      styles.categoryDot,
                      { backgroundColor: CATEGORY_COLORS[entry.category] || Colors.dark.primary },
                    ]}
                  />
                  <View style={styles.categoryInfo}>
                    <Text style={styles.categoryName}>{entry.category}</Text>
                    <Text style={styles.categorySpend}>
                      {(entry.rate * 100).toFixed(0)}% on ${entry.spendAmount.toFixed(2)}
                    </Text>
                  </View>
                  <Text style={styles.categoryCashback}>+${entry.cashbackAmount.toFixed(2)}</Text>
                </View>
              ))}
            </View>
          </>
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  content: {
    padding: 20,
    paddingBottom: 60,
  },
  heroCard: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 28,
    alignItems: "center" as const,
    gap: 8,
    marginBottom: 16,
  },
  heroValue: {
    fontSize: 36,
    fontWeight: "800" as const,
    color: Colors.dark.text,
  },
  heroLabel: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
  },
  demoNotice: {
    backgroundColor: `${Colors.dark.warning}1A`,
    borderRadius: 12,
    padding: 12,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: `${Colors.dark.warning}40`,
  },
  demoNoticeText: {
    fontSize: 12,
    color: Colors.dark.warning,
    lineHeight: 16,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 12,
    marginTop: 8,
  },
  categoryList: {
    gap: 10,
    marginBottom: 8,
  },
  categoryRow: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
    gap: 12,
  },
  categoryDot: {
    width: 10,
    height: 10,
    borderRadius: 5,
  },
  categoryInfo: {
    flex: 1,
  },
  categoryName: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  categorySpend: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  categoryCashback: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.success,
  },
  emptyState: {
    alignItems: "center" as const,
    padding: 40,
    gap: 12,
  },
  emptyText: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 18,
  },
});
