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

import Colors from "@/constants/colors";
import { useDemoLedger } from "@/lib/demo-ledger";
import { showAlert } from "@/lib/utils/alert";
import { hapticToggle, hapticSuccess } from "@/lib/ui/haptics";

// Auto-Round-Up Pots - every payment gets rounded up to the next dollar
// while this is on, and the spare change goes straight into a separate
// pot instead of just sitting in the main balance unnoticed.
export default function RoundUpPotScreen() {
  const insets = useSafeAreaInsets();
  const roundUpEnabled = useDemoLedger((s) => s.roundUpEnabled);
  const roundUpPot = useDemoLedger((s) => s.roundUpPot);
  const lifetimeTotal = useDemoLedger((s) => s.roundUpLifetimeTotal);
  const setRoundUpEnabled = useDemoLedger((s) => s.setRoundUpEnabled);
  const withdrawRoundUpPot = useDemoLedger((s) => s.withdrawRoundUpPot);
  const transactions = useDemoLedger((s) => s.transactions);

  const recentRoundUps = transactions
    .filter((t) => !!t.roundUpAmount)
    .slice(0, 12);

  const handleWithdraw = () => {
    if (roundUpPot <= 0) {
      showAlert("Nothing to move yet", "Your pot fills up automatically as you spend with round-up turned on.");
      return;
    }
    withdrawRoundUpPot();
    hapticSuccess();
    showAlert("Moved to your balance", `$${roundUpPot.toFixed(2)} is back in your main balance.`);
  };

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

      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
        <View style={styles.potCard}>
          <PiggyBank color={Colors.dark.success} size={36} />
          <Text style={styles.potLabel}>In your pot</Text>
          <Text style={styles.potAmount}>${roundUpPot.toFixed(2)}</Text>
          <Text style={styles.potLifetime}>${lifetimeTotal.toFixed(2)} saved in spare change overall</Text>
          <TouchableOpacity style={styles.withdrawButton} onPress={handleWithdraw} activeOpacity={0.85}>
            <Text style={styles.withdrawButtonText}>Move to Balance</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.toggleCard}>
          <View style={styles.toggleLeft}>
            <Coins color={Colors.dark.primary} size={20} />
            <View>
              <Text style={styles.toggleTitle}>Round up future payments</Text>
              <Text style={styles.toggleSubtitle}>Rounds sends and purchases up to the next dollar</Text>
            </View>
          </View>
          <Switch
            value={roundUpEnabled}
            onValueChange={(value) => {
              hapticToggle();
              setRoundUpEnabled(value);
            }}
            trackColor={{ false: Colors.dark.surfaceElevated, true: Colors.dark.primary }}
            thumbColor={Colors.dark.background}
          />
        </View>

        <Text style={styles.sectionTitle}>Recent round-ups</Text>
        {recentRoundUps.length === 0 ? (
          <Text style={styles.emptyText}>
            Once round-up is on, every send or purchase that isn't a whole dollar amount will show up here.
          </Text>
        ) : (
          recentRoundUps.map((t) => (
            <View key={t.id} style={styles.roundUpRow}>
              <Text style={styles.roundUpName}>{t.counterpartyName}</Text>
              <Text style={styles.roundUpAmount}>+${t.roundUpAmount?.toFixed(2)}</Text>
            </View>
          ))
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  content: {
    padding: 20,
    paddingBottom: 60,
  },
  potCard: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 28,
    alignItems: "center" as const,
    marginBottom: 20,
  },
  potLabel: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    marginTop: 10,
  },
  potAmount: {
    fontSize: 40,
    fontWeight: "800" as const,
    color: Colors.dark.text,
    marginTop: 4,
  },
  potLifetime: {
    fontSize: 12,
    color: Colors.dark.textTertiary,
    marginTop: 6,
    marginBottom: 16,
  },
  withdrawButton: {
    backgroundColor: Colors.dark.success,
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 24,
  },
  withdrawButtonText: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: "#FFFFFF",
  },
  toggleCard: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    justifyContent: "space-between",
    backgroundColor: Colors.dark.surface,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
    marginBottom: 24,
  },
  toggleLeft: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 12,
    flex: 1,
  },
  toggleTitle: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  toggleSubtitle: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginTop: 2,
    maxWidth: 220,
  },
  sectionTitle: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 12,
  },
  emptyText: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    lineHeight: 19,
  },
  roundUpRow: {
    flexDirection: "row" as const,
    justifyContent: "space-between",
    backgroundColor: Colors.dark.surface,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
    marginBottom: 8,
  },
  roundUpName: {
    fontSize: 14,
    color: Colors.dark.text,
  },
  roundUpAmount: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.success,
  },
});
