import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Switch,
  ActivityIndicator,
  Modal,
  Platform,
  Alert,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Stack } from "expo-router";
import { Briefcase, PiggyBank, Wallet, ArrowRightLeft, X, Coins, Plus, Trash2, Target, Bitcoin, LineChart, Zap } from "lucide-react-native";

import Colors from "@/constants/colors";
import { trpc } from "@/lib/trpc";
import { useAuth } from "@/lib/auth-context";
import { LedgerBalanceCard } from "@/components/LedgerBalanceCard";
import { showAlert } from "@/lib/utils/alert";

type WalletKey = "everyday" | "savings" | "business";
type RiskTolerance = "conservative" | "balanced" | "aggressive";

const WALLET_META: Record<WalletKey, { label: string; icon: typeof Wallet; color: string }> = {
  everyday: { label: "Everyday", icon: Wallet, color: Colors.dark.primary },
  savings: { label: "Savings", icon: PiggyBank, color: Colors.dark.success },
  business: { label: "Business", icon: Briefcase, color: Colors.dark.secondary },
};

const ACCOUNT_ICONS: Record<string, typeof Wallet> = {
  everyday: Wallet,
  savings: PiggyBank,
  business: Briefcase,
  bitcoin: Bitcoin,
  stocks: LineChart,
};

export default function WalletsScreen() {
  const insets = useSafeAreaInsets();
  const { isDemoMode } = useAuth();
  const [transferFrom, setTransferFrom] = useState<WalletKey | null>(null);
  const [transferTo, setTransferTo] = useState<WalletKey | null>(null);
  const [amount, setAmount] = useState("");
  const [showNewGoal, setShowNewGoal] = useState(false);
  const [goalName, setGoalName] = useState("");
  const [goalTarget, setGoalTarget] = useState("");
  const [contributeGoalId, setContributeGoalId] = useState<string | null>(null);
  const [contributeAmount, setContributeAmount] = useState("");
  const [autopilotGoalId, setAutopilotGoalId] = useState<string | null>(null);
  const [autopilotRisk, setAutopilotRisk] = useState<RiskTolerance>("balanced");

  const walletsQuery = trpc.wallets.get.useQuery(undefined, { enabled: !isDemoMode });
  const orchestrationQuery = trpc.wallets.orchestration.useQuery(undefined, { enabled: !isDemoMode });
  const goalsQuery = trpc.savingsGoals.list.useQuery(undefined, { enabled: !isDemoMode });
  const autopilotQuery = trpc.savingsGoals.autopilotSuggestion.useQuery(
    { goalId: autopilotGoalId ?? "", riskTolerance: autopilotRisk },
    { enabled: !!autopilotGoalId && !isDemoMode }
  );
  const enableAutopilotMutation = trpc.automation.createRule.useMutation({
    onSuccess: () => {
      showAlert("Autopilot enabled", "Zendo will move money toward this goal on a weekly schedule.");
      setAutopilotGoalId(null);
    },
    onError: (err) => {
      Alert.alert(
        "Couldn't enable autopilot",
        `${err.message}${err.message.toLowerCase().includes("bundle") ? " Subscribe to Zendo Automation first." : ""}`
      );
    },
  });

  const createGoalMutation = trpc.savingsGoals.create.useMutation({
    onSuccess: () => {
      goalsQuery.refetch();
      setShowNewGoal(false);
      setGoalName("");
      setGoalTarget("");
    },
    onError: () => showAlert("Error", "Failed to load wallet balances."),
  });

  const contributeMutation = trpc.savingsGoals.contribute.useMutation({
    onSuccess: () => {
      goalsQuery.refetch();
      walletsQuery.refetch();
      setContributeGoalId(null);
      setContributeAmount("");
      showAlert("Set Aside", "Money moved into your goal.");
    },
    onError: () => showAlert("Error", "Failed to create wallet."),
  });

  const withdrawGoalMutation = trpc.savingsGoals.withdraw.useMutation({
    onSuccess: () => {
      goalsQuery.refetch();
      walletsQuery.refetch();
      showAlert("Moved Back", "Money is back in Everyday.");
    },
    onError: () => showAlert("Error", "Failed to top up wallet."),
  });

  const deleteGoalMutation = trpc.savingsGoals.delete.useMutation({
    onSuccess: () => {
      goalsQuery.refetch();
      walletsQuery.refetch();
    },
    onError: () => showAlert("Error", "Failed to withdraw from wallet."),
  });
  const transferMutation = trpc.wallets.transfer.useMutation({
    onSuccess: () => {
      walletsQuery.refetch();
      setTransferFrom(null);
      setTransferTo(null);
      setAmount("");
      showAlert("Moved", "Your money has been moved between wallets.");
    },
    onError: () => showAlert("Error", "Failed to transfer between wallets."),
  });
  const toggleRoundUpsMutation = trpc.wallets.toggleRoundUps.useMutation({
    onSuccess: () => walletsQuery.refetch(),
  });

  const demoWallets = { everyday: 8500, savings: 3200, business: 847.83 };
  const wallets = isDemoMode ? demoWallets : walletsQuery.data?.wallets;
  const roundUpsEnabled = isDemoMode ? true : walletsQuery.data?.roundUpsEnabled ?? false;

  const demoGoals = [
    { id: "demo-goal-1", name: "Rainy Day Fund", targetAmount: 2000, currentAmount: 850 },
  ];
  const goals = isDemoMode ? demoGoals : goalsQuery.data?.goals ?? [];

  const handleCreateGoal = () => {
    if (!goalName.trim()) {
      showAlert("Name it", "Give your goal a name, like \u201cRainy Day Fund\u201d.");
      return;
    }
    if (isDemoMode) {
      showAlert("Demo Mode", "Creating goals needs a real account.");
      return;
    }
    const target = goalTarget.trim() ? parseFloat(goalTarget) : undefined;
    createGoalMutation.mutate({ name: goalName.trim(), targetAmount: target });
  };

  const handleContribute = () => {
    if (!contributeGoalId) return;
    const amountNum = parseFloat(contributeAmount);
    if (isNaN(amountNum) || amountNum <= 0) {
      showAlert("Invalid Amount", "Enter a valid amount to set aside");
      return;
    }
    if (isDemoMode) {
      showAlert("Demo Mode", "Setting money aside needs a real account.");
      return;
    }
    contributeMutation.mutate({ goalId: contributeGoalId, amount: amountNum, source: "everyday" });
  };

  const handleWithdrawGoal = (goalId: string, currentAmount: number) => {
    if (isDemoMode) {
      showAlert("Demo Mode", "Moving money back needs a real account.");
      return;
    }
    if (currentAmount <= 0) return;
    withdrawGoalMutation.mutate({ goalId, amount: currentAmount });
  };

  const handleDeleteGoal = (goalId: string) => {
    if (isDemoMode) {
      showAlert("Demo Mode", "Deleting goals needs a real account.");
      return;
    }
    deleteGoalMutation.mutate({ goalId });
  };
  const handleTransfer = () => {
    if (!transferFrom || !transferTo) return;
    const amountNum = parseFloat(amount);
    if (isNaN(amountNum) || amountNum <= 0) {
      showAlert("Invalid Amount", "Enter a valid amount to move");
      return;
    }
    if (isDemoMode) {
      showAlert("Demo Mode", "Wallet transfers need a real account.");
      return;
    }
    transferMutation.mutate({ from: transferFrom, to: transferTo, amount: amountNum });
  };

  if (!wallets) {
    return (
      <View style={[styles.container, { paddingTop: insets.top }]}>
        <Stack.Screen options={{ title: "Wallets", headerShown: true }} />
        <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 60 }} />
      </View>
    );
  }

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

      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
        {!isDemoMode && (
          <View style={styles.ledgerSection}>
            <LedgerBalanceCard variant="compact" style={styles.ledgerCard} />
          </View>
        )}

        <Text style={styles.intro}>
          Keep your money separated without opening separate accounts. Sending and spending pulls
          from Everyday by default.
        </Text>

        {orchestrationQuery.data && (
          <View style={styles.netWorthCard}>
            <Text style={styles.netWorthLabel}>Total across every account</Text>
            <Text style={styles.netWorthValue}>${orchestrationQuery.data.netWorth.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</Text>
            <View style={styles.accountsRow}>
              {orchestrationQuery.data.accounts.map((a) => {
                const Icon = ACCOUNT_ICONS[a.id] ?? Wallet;
                return (
                  <View key={a.id} style={styles.accountChip}>
                    <Icon size={14} color={Colors.dark.primary} />
                    <Text style={styles.accountChipLabel}>{a.label}</Text>
                    <Text style={styles.accountChipValue}>${a.balance.toFixed(0)}</Text>
                  </View>
                );
              })}
            </View>
            {orchestrationQuery.data.orchestrationRules.length > 0 && (
              <Text style={styles.netWorthFootnote}>
                {orchestrationQuery.data.orchestrationRules.length} automation rule{orchestrationQuery.data.orchestrationRules.length === 1 ? "" : "s"} actively moving money for you.
              </Text>
            )}
          </View>
        )}

        <View style={styles.walletList}>
          {(Object.keys(WALLET_META) as WalletKey[]).map((key) => {
            const meta = WALLET_META[key];
            const Icon = meta.icon;
            return (
              <View key={key} style={styles.walletCard}>
                <View style={[styles.walletIcon, { backgroundColor: `${meta.color}20` }]}>
                  <Icon color={meta.color} size={22} />
                </View>
                <View style={styles.walletInfo}>
                  <Text style={styles.walletLabel}>{meta.label}</Text>
                  <Text style={styles.walletBalance}>${wallets[key].toFixed(2)}</Text>
                </View>
                <TouchableOpacity
                  style={styles.moveButton}
                  onPress={() => {
                    setTransferFrom(key);
                    setTransferTo(null);
                  }}
                >
                  <ArrowRightLeft size={14} color={Colors.dark.primary} />
                  <Text style={styles.moveButtonText}>Move</Text>
                </TouchableOpacity>
              </View>
            );
          })}
        </View>

        <View style={styles.roundUpsCard}>
          <View style={styles.roundUpsLeft}>
            <Coins color={Colors.dark.success} size={22} />
            <View style={styles.roundUpsTextWrap}>
              <Text style={styles.roundUpsTitle}>Round-Ups</Text>
              <Text style={styles.roundUpsSubtitle}>
                Round every Everyday payment up to the nearest dollar and stash the change in Savings.
              </Text>
            </View>
          </View>
          <Switch
            value={roundUpsEnabled}
            onValueChange={(value) => {
              if (isDemoMode) {
                showAlert("Demo Mode", "Round-ups need a real account to persist.");
                return;
              }
              toggleRoundUpsMutation.mutate({ enabled: value });
            }}
            trackColor={{ false: Colors.dark.border, true: `${Colors.dark.success}80` }}
            thumbColor={roundUpsEnabled ? Colors.dark.success : "#f4f3f4"}
          />
        </View>

        <View style={styles.goalsHeader}>
          <Text style={styles.goalsTitle}>Savings Goals</Text>
          <TouchableOpacity style={styles.addGoalButton} onPress={() => setShowNewGoal(true)}>
            <Plus size={14} color={Colors.dark.primary} />
            <Text style={styles.addGoalButtonText}>New Goal</Text>
          </TouchableOpacity>
        </View>
        <Text style={styles.goalsSubtitle}>
          A rainy day fund, a trip, anything - set money aside inside Savings and pull it back out
          anytime.
        </Text>

        {goals.length === 0 ? (
          <View style={styles.goalsEmpty}>
            <Target size={32} color={Colors.dark.textTertiary} />
            <Text style={styles.goalsEmptyText}>No goals yet. Start with a Rainy Day Fund.</Text>
          </View>
        ) : (
          <View style={styles.goalsList}>
            {goals.map((goal) => {
              const progress = goal.targetAmount
                ? Math.min(1, goal.currentAmount / goal.targetAmount)
                : null;
              return (
                <View key={goal.id} style={styles.goalCard}>
                  <View style={styles.goalCardTop}>
                    <Text style={styles.goalName}>{goal.name}</Text>
                    <TouchableOpacity onPress={() => handleDeleteGoal(goal.id)}>
                      <Trash2 size={15} color={Colors.dark.textTertiary} />
                    </TouchableOpacity>
                  </View>
                  <Text style={styles.goalAmount}>
                    ${goal.currentAmount.toFixed(2)}
                    {goal.targetAmount ? ` of $${goal.targetAmount.toFixed(2)}` : ""}
                  </Text>
                  {progress !== null && (
                    <View style={styles.goalProgressTrack}>
                      <View style={[styles.goalProgressFill, { width: `${progress * 100}%` }]} />
                    </View>
                  )}
                  <View style={styles.goalActions}>
                    <TouchableOpacity
                      style={styles.goalActionButton}
                      onPress={() => setContributeGoalId(goal.id)}
                    >
                      <Text style={styles.goalActionButtonText}>Add Money</Text>
                    </TouchableOpacity>
                    {goal.currentAmount > 0 && (
                      <TouchableOpacity
                        style={styles.goalActionButtonSecondary}
                        onPress={() => handleWithdrawGoal(goal.id, goal.currentAmount)}
                      >
                        <Text style={styles.goalActionButtonSecondaryText}>Move Back</Text>
                      </TouchableOpacity>
                    )}
                    {!isDemoMode && (
                      <TouchableOpacity
                        style={styles.goalActionButtonSecondary}
                        onPress={() => setAutopilotGoalId(autopilotGoalId === goal.id ? null : goal.id)}
                      >
                        <Zap size={12} color={Colors.dark.primary} />
                        <Text style={styles.goalActionButtonSecondaryText}> Autopilot</Text>
                      </TouchableOpacity>
                    )}
                  </View>

                  {autopilotGoalId === goal.id && (
                    <View style={styles.autopilotPanel}>
                      <View style={styles.riskRow}>
                        {(["conservative", "balanced", "aggressive"] as RiskTolerance[]).map((r) => (
                          <TouchableOpacity
                            key={r}
                            style={[styles.riskChip, autopilotRisk === r && styles.riskChipActive]}
                            onPress={() => setAutopilotRisk(r)}
                          >
                            <Text style={[styles.riskChipText, autopilotRisk === r && styles.riskChipTextActive]}>
                              {r.charAt(0).toUpperCase() + r.slice(1)}
                            </Text>
                          </TouchableOpacity>
                        ))}
                      </View>
                      {autopilotQuery.isLoading ? (
                        <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 10 }} />
                      ) : autopilotQuery.data ? (
                        <>
                          <Text style={styles.autopilotSuggestion}>
                            Suggested ${autopilotQuery.data.suggestedWeeklyContribution.toFixed(2)}/week
                            {autopilotQuery.data.estimatedWeeksToGoal
                              ? ` - reaches your goal in ~${autopilotQuery.data.estimatedWeeksToGoal} week${autopilotQuery.data.estimatedWeeksToGoal === 1 ? "" : "s"}`
                              : ""}
                          </Text>
                          <TouchableOpacity
                            style={styles.goalActionButton}
                            disabled={enableAutopilotMutation.isPending || autopilotQuery.data.suggestedWeeklyContribution <= 0}
                            onPress={() =>
                              enableAutopilotMutation.mutate({
                                name: `Autopilot: ${goal.name}`,
                                trigger: "scheduled",
                                triggerConfig: { frequency: "weekly" },
                                action: "auto_save",
                                actionConfig: { goalId: goal.id, amount: autopilotQuery.data!.suggestedWeeklyContribution },
                              })
                            }
                          >
                            {enableAutopilotMutation.isPending ? (
                              <ActivityIndicator color={Colors.dark.background} size="small" />
                            ) : (
                              <Text style={styles.goalActionButtonText}>Enable autopilot</Text>
                            )}
                          </TouchableOpacity>
                        </>
                      ) : null}
                    </View>
                  )}
                </View>
              );
            })}
          </View>
        )}
      </ScrollView>

      <Modal
        visible={!!transferFrom}
        animationType="slide"
        transparent
        onRequestClose={() => setTransferFrom(null)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Move Money</Text>
              <TouchableOpacity onPress={() => setTransferFrom(null)}>
                <X size={22} color={Colors.dark.textSecondary} />
              </TouchableOpacity>
            </View>

            <Text style={styles.modalLabel}>From</Text>
            <View style={styles.walletPicker}>
              {(Object.keys(WALLET_META) as WalletKey[]).map((key) => (
                <TouchableOpacity
                  key={key}
                  style={[styles.walletChip, transferFrom === key && styles.walletChipActive]}
                  onPress={() => setTransferFrom(key)}
                >
                  <Text style={[styles.walletChipText, transferFrom === key && styles.walletChipTextActive]}>
                    {WALLET_META[key].label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            <Text style={styles.modalLabel}>To</Text>
            <View style={styles.walletPicker}>
              {(Object.keys(WALLET_META) as WalletKey[])
                .filter((key) => key !== transferFrom)
                .map((key) => (
                  <TouchableOpacity
                    key={key}
                    style={[styles.walletChip, transferTo === key && styles.walletChipActive]}
                    onPress={() => setTransferTo(key)}
                  >
                    <Text style={[styles.walletChipText, transferTo === key && styles.walletChipTextActive]}>
                      {WALLET_META[key].label}
                    </Text>
                  </TouchableOpacity>
                ))}
            </View>

            <Text style={styles.modalLabel}>Amount</Text>
            <TextInput
              style={styles.amountInput}
              value={amount}
              onChangeText={setAmount}
              placeholder="$0.00"
              placeholderTextColor={Colors.dark.textTertiary}
              keyboardType="decimal-pad"
            />

            <TouchableOpacity
              style={[styles.confirmButton, (!transferTo || !amount) && styles.confirmButtonDisabled]}
              onPress={handleTransfer}
              disabled={!transferTo || !amount || transferMutation.isPending}
            >
              {transferMutation.isPending ? (
                <ActivityIndicator color={Colors.dark.background} />
              ) : (
                <Text style={styles.confirmButtonText}>Move Money</Text>
              )}
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      <Modal
        visible={showNewGoal}
        animationType="slide"
        transparent
        onRequestClose={() => setShowNewGoal(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>New Savings Goal</Text>
              <TouchableOpacity onPress={() => setShowNewGoal(false)}>
                <X size={22} color={Colors.dark.textSecondary} />
              </TouchableOpacity>
            </View>

            <Text style={styles.modalLabel}>Name</Text>
            <TextInput
              style={styles.amountInput}
              value={goalName}
              onChangeText={setGoalName}
              placeholder="Rainy Day Fund"
              placeholderTextColor={Colors.dark.textTertiary}
            />

            <Text style={styles.modalLabel}>Target (optional)</Text>
            <TextInput
              style={styles.amountInput}
              value={goalTarget}
              onChangeText={setGoalTarget}
              placeholder="$0.00"
              placeholderTextColor={Colors.dark.textTertiary}
              keyboardType="decimal-pad"
            />

            <TouchableOpacity
              style={styles.confirmButton}
              onPress={handleCreateGoal}
              disabled={createGoalMutation.isPending}
            >
              {createGoalMutation.isPending ? (
                <ActivityIndicator color={Colors.dark.background} />
              ) : (
                <Text style={styles.confirmButtonText}>Create Goal</Text>
              )}
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      <Modal
        visible={!!contributeGoalId}
        animationType="slide"
        transparent
        onRequestClose={() => setContributeGoalId(null)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Set Money Aside</Text>
              <TouchableOpacity onPress={() => setContributeGoalId(null)}>
                <X size={22} color={Colors.dark.textSecondary} />
              </TouchableOpacity>
            </View>

            <Text style={styles.modalLabel}>Amount from Everyday</Text>
            <TextInput
              style={styles.amountInput}
              value={contributeAmount}
              onChangeText={setContributeAmount}
              placeholder="$0.00"
              placeholderTextColor={Colors.dark.textTertiary}
              keyboardType="decimal-pad"
            />

            <TouchableOpacity
              style={styles.confirmButton}
              onPress={handleContribute}
              disabled={contributeMutation.isPending}
            >
              {contributeMutation.isPending ? (
                <ActivityIndicator color={Colors.dark.background} />
              ) : (
                <Text style={styles.confirmButtonText}>Add to Goal</Text>
              )}
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  content: {
    padding: 20,
    paddingBottom: 60,
  },
  ledgerSection: {
    marginBottom: 20,
  },
  ledgerCard: {
    marginBottom: 0,
  },
  intro: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    lineHeight: 19,
    marginBottom: 20,
  },
  netWorthCard: {
    backgroundColor: Colors.dark.primary,
    borderRadius: 18,
    padding: 20,
    marginBottom: 20,
    gap: 10,
  },
  netWorthLabel: {
    fontSize: 12,
    color: "rgba(255,255,255,0.65)",
    textTransform: "uppercase" as const,
  },
  netWorthValue: {
    fontSize: 28,
    fontWeight: "800" as const,
    color: "#fff",
  },
  accountsRow: {
    flexDirection: "row" as const,
    flexWrap: "wrap" as const,
    gap: 8,
  },
  accountChip: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 5,
    backgroundColor: "rgba(255,255,255,0.15)",
    borderRadius: 10,
    paddingHorizontal: 10,
    paddingVertical: 6,
  },
  accountChipLabel: {
    fontSize: 11,
    color: "rgba(255,255,255,0.85)",
    fontWeight: "600" as const,
  },
  accountChipValue: {
    fontSize: 11,
    color: "#fff",
    fontWeight: "700" as const,
  },
  netWorthFootnote: {
    fontSize: 11,
    color: "rgba(255,255,255,0.7)",
  },
  autopilotPanel: {
    marginTop: 10,
    paddingTop: 10,
    borderTopWidth: 1,
    borderTopColor: Colors.dark.border,
    gap: 10,
  },
  riskRow: {
    flexDirection: "row" as const,
    gap: 6,
  },
  riskChip: {
    flex: 1,
    alignItems: "center" as const,
    paddingVertical: 8,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: Colors.dark.border,
  },
  riskChipActive: {
    borderColor: Colors.dark.primary,
    backgroundColor: `${Colors.dark.primary}1A`,
  },
  riskChipText: {
    fontSize: 11,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  riskChipTextActive: {
    color: Colors.dark.primary,
  },
  autopilotSuggestion: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    lineHeight: 17,
  },
  walletList: {
    gap: 12,
    marginBottom: 24,
  },
  walletCard: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    backgroundColor: Colors.dark.surface,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
    gap: 14,
  },
  walletIcon: {
    width: 44,
    height: 44,
    borderRadius: 22,
    alignItems: "center" as const,
    justifyContent: "center" as const,
  },
  walletInfo: {
    flex: 1,
  },
  walletLabel: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
  },
  walletBalance: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginTop: 2,
  },
  moveButton: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 5,
    backgroundColor: `${Colors.dark.primary}1A`,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 10,
  },
  moveButtonText: {
    fontSize: 12,
    fontWeight: "700" as const,
    color: Colors.dark.primary,
  },
  roundUpsCard: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    backgroundColor: Colors.dark.surface,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
    gap: 12,
  },
  roundUpsLeft: {
    flex: 1,
    flexDirection: "row" as const,
    gap: 12,
    alignItems: "flex-start" as const,
  },
  roundUpsTextWrap: {
    flex: 1,
  },
  roundUpsTitle: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 4,
  },
  roundUpsSubtitle: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    lineHeight: 17,
  },
  goalsHeader: {
    flexDirection: "row" as const,
    justifyContent: "space-between" as const,
    alignItems: "center" as const,
    marginTop: 28,
  },
  goalsTitle: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  addGoalButton: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 5,
    backgroundColor: `${Colors.dark.primary}1A`,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderRadius: 8,
  },
  addGoalButtonText: {
    fontSize: 12,
    fontWeight: "700" as const,
    color: Colors.dark.primary,
  },
  goalsSubtitle: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    lineHeight: 17,
    marginTop: 8,
    marginBottom: 16,
  },
  goalsEmpty: {
    alignItems: "center" as const,
    paddingVertical: 30,
    gap: 10,
  },
  goalsEmptyText: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
  },
  goalsList: {
    gap: 12,
  },
  goalCard: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
  },
  goalCardTop: {
    flexDirection: "row" as const,
    justifyContent: "space-between" as const,
    alignItems: "center" as const,
  },
  goalName: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  goalAmount: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    marginTop: 4,
  },
  goalProgressTrack: {
    height: 6,
    borderRadius: 3,
    backgroundColor: Colors.dark.surfaceElevated,
    marginTop: 10,
    overflow: "hidden" as const,
  },
  goalProgressFill: {
    height: 6,
    borderRadius: 3,
    backgroundColor: Colors.dark.success,
  },
  goalActions: {
    flexDirection: "row" as const,
    gap: 8,
    marginTop: 12,
  },
  goalActionButton: {
    flex: 1,
    alignItems: "center" as const,
    paddingVertical: 9,
    borderRadius: 9,
    backgroundColor: Colors.dark.primary,
  },
  goalActionButtonText: {
    fontSize: 12,
    fontWeight: "700" as const,
    color: Colors.dark.background,
  },
  goalActionButtonSecondary: {
    flex: 1,
    flexDirection: "row" as const,
    alignItems: "center" as const,
    justifyContent: "center" as const,
    gap: 4,
    paddingVertical: 9,
    borderRadius: 9,
    borderWidth: 1,
    borderColor: Colors.dark.border,
  },
  goalActionButtonSecondaryText: {
    fontSize: 12,
    fontWeight: "700" as const,
    color: Colors.dark.textSecondary,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: "rgba(0,0,0,0.5)",
    justifyContent: "flex-end" as const,
  },
  modalContent: {
    backgroundColor: Colors.dark.card,
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    padding: 24,
  },
  modalHeader: {
    flexDirection: "row" as const,
    justifyContent: "space-between" as const,
    alignItems: "center" as const,
    marginBottom: 20,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  modalLabel: {
    fontSize: 12,
    fontWeight: "700" as const,
    color: Colors.dark.textSecondary,
    textTransform: "uppercase" as const,
    marginBottom: 8,
    marginTop: 12,
  },
  walletPicker: {
    flexDirection: "row" as const,
    gap: 8,
  },
  walletChip: {
    flex: 1,
    alignItems: "center" as const,
    paddingVertical: 10,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    backgroundColor: Colors.dark.surfaceElevated,
  },
  walletChipActive: {
    borderColor: Colors.dark.primary,
    backgroundColor: `${Colors.dark.primary}1A`,
  },
  walletChipText: {
    fontSize: 13,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  walletChipTextActive: {
    color: Colors.dark.primary,
  },
  amountInput: {
    backgroundColor: Colors.dark.surfaceElevated,
    borderRadius: 12,
    padding: 14,
    fontSize: 18,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    ...Platform.select({
      web: { outlineStyle: "none" as const },
    }),
  },
  confirmButton: {
    backgroundColor: Colors.dark.primary,
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: "center" as const,
    marginTop: 24,
  },
  confirmButtonDisabled: {
    opacity: 0.5,
  },
  confirmButtonText: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.background,
  },
});
