import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  ActivityIndicator,
  TouchableOpacity,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Stack, useRouter } from "expo-router";
import { TrendingDown, AlertTriangle, Calendar, CheckCircle2, ShieldCheck } from "lucide-react-native";

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

export default function CashFlowScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { isDemoMode } = useAuth();

  const forecastQuery = trpc.insights.cashFlow.useQuery(undefined, { enabled: !isDemoMode });
  const shieldQuery = trpc.insights.billShield.useQuery(undefined, { enabled: !isDemoMode });
  const utils = trpc.useUtils();
  const activateMutation = trpc.insights.activateShield.useMutation({
    onSuccess: (result) => {
      showAlert("Bill Shield activated", `Moved $${result.shieldedAmount.toFixed(2)} into Savings as a buffer.`);
      utils.insights.cashFlow.invalidate();
      utils.insights.billShield.invalidate();
      utils.wallets.get.invalidate();
    },
    onError: (err) => showAlert("Couldn't activate Bill Shield", err.message),
  });
  const data = forecastQuery.data;
  const shield = shieldQuery.data;

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

      {isDemoMode ? (
        <View style={styles.emptyState}>
          <TrendingDown size={48} color={Colors.dark.textTertiary} />
          <Text style={styles.emptyText}>Cash flow forecasting needs a real account with transaction history.</Text>
        </View>
      ) : forecastQuery.isLoading ? (
        <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 60 }} />
      ) : !data ? (
        <View style={styles.emptyState}>
          <Text style={styles.emptyText}>Couldn&apos;t load your forecast.</Text>
        </View>
      ) : (
        <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
          <View
            style={[
              styles.statusCard,
              data.willRunLow ? styles.statusCardWarning : styles.statusCardGood,
            ]}
          >
            {data.willRunLow ? (
              <AlertTriangle color={Colors.dark.warning} size={32} />
            ) : (
              <CheckCircle2 color={Colors.dark.success} size={32} />
            )}
            <Text style={styles.statusTitle}>
              {data.willRunLow
                ? `Projected to run low in ${data.daysUntilShortfall} day${data.daysUntilShortfall === 1 ? "" : "s"}`
                : "You're on track for the next 30 days"}
            </Text>
            <Text style={styles.statusSubtitle}>
              {data.willRunLow
                ? `Based on your spending pace and upcoming bills, your balance could go negative around ${new Date(
                    data.projectedShortfallDate!
                  ).toLocaleDateString("en-US", { month: "short", day: "numeric" })}.`
                : "Your current balance comfortably covers your recent spending pace and known upcoming bills."}
            </Text>
          </View>

          <View style={styles.statsRow}>
            <View style={styles.statBox}>
              <Text style={styles.statValue}>${data.currentBalance.toFixed(2)}</Text>
              <Text style={styles.statLabel}>Current Balance</Text>
            </View>
            <View style={styles.statBox}>
              <Text style={styles.statValue}>${data.averageDailySpend.toFixed(2)}</Text>
              <Text style={styles.statLabel}>Avg. Daily Spend</Text>
            </View>
          </View>

          {shield && (
            <View style={styles.shieldCard}>
              <View style={styles.shieldHeader}>
                <ShieldCheck size={20} color="#6366F1" />
                <Text style={styles.shieldTitle}>Predictive Bill Shield</Text>
              </View>
              <Text style={styles.shieldDetail}>
                Recommended buffer to move into Savings now: ${shield.recommendedShieldAmount.toFixed(2)}
                {shield.tightestDay && shield.tightestDay.balance < 0
                  ? ` - your tightest projected day is ${new Date(shield.tightestDay.date).toLocaleDateString("en-US", { month: "short", day: "numeric" })}.`
                  : "."}
              </Text>
              {shield.estimatedOverdraftsAvoidedPerYear > 0 && (
                <Text style={styles.shieldStat}>
                  ~{shield.estimatedOverdraftsAvoidedPerYear} potential overdraft moment{shield.estimatedOverdraftsAvoidedPerYear === 1 ? "" : "s"}/yr shielded against
                </Text>
              )}
              <TouchableOpacity
                style={styles.shieldButton}
                disabled={shield.recommendedShieldAmount <= 0 || activateMutation.isPending}
                onPress={() => activateMutation.mutate({ amount: shield.recommendedShieldAmount })}
              >
                {activateMutation.isPending ? (
                  <ActivityIndicator color="#fff" size="small" />
                ) : (
                  <Text style={styles.shieldButtonText}>
                    {shield.recommendedShieldAmount > 0 ? `Shield $${shield.recommendedShieldAmount.toFixed(2)} now` : "No buffer needed right now"}
                  </Text>
                )}
              </TouchableOpacity>
              <Text style={styles.shieldFootnote}>
                For ongoing automatic protection every cycle, set up a recurring rule from Wallets → Automation.
              </Text>
            </View>
          )}

          {data.upcomingRecurring.length > 0 && (
            <>
              <Text style={styles.sectionTitle}>Upcoming bills (next 30 days)</Text>
              <View style={styles.list}>
                {data.upcomingRecurring.map((r, i) => (
                  <View key={i} style={styles.billRow}>
                    <Calendar color={Colors.dark.textSecondary} size={16} />
                    <View style={styles.billInfo}>
                      <Text style={styles.billNote}>{r.note || "Recurring payment"}</Text>
                      <Text style={styles.billDate}>
                        {new Date(r.date).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                      </Text>
                    </View>
                    <Text style={styles.billAmount}>${r.amount.toFixed(2)}</Text>
                  </View>
                ))}
              </View>
            </>
          )}

          {data.willRunLow && (
            <TouchableOpacity style={styles.actionButton} onPress={() => router.push("/wallets")}>
              <Text style={styles.actionButtonText}>Move money from Savings</Text>
            </TouchableOpacity>
          )}
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  content: {
    padding: 20,
    paddingBottom: 60,
  },
  emptyState: {
    alignItems: "center" as const,
    marginTop: 80,
    gap: 12,
    paddingHorizontal: 30,
  },
  emptyText: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 18,
  },
  statusCard: {
    alignItems: "center" as const,
    borderRadius: 18,
    padding: 24,
    gap: 10,
    borderWidth: 1,
  },
  statusCardWarning: {
    backgroundColor: `${Colors.dark.warning}14`,
    borderColor: `${Colors.dark.warning}40`,
  },
  statusCardGood: {
    backgroundColor: `${Colors.dark.success}14`,
    borderColor: `${Colors.dark.success}40`,
  },
  statusTitle: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    textAlign: "center" as const,
  },
  statusSubtitle: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 18,
  },
  statsRow: {
    flexDirection: "row" as const,
    gap: 12,
    marginTop: 16,
  },
  statBox: {
    flex: 1,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
    alignItems: "center" as const,
  },
  statValue: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  statLabel: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginTop: 4,
  },
  shieldCard: {
    backgroundColor: "#EEF2FF",
    borderRadius: 16,
    borderWidth: 1,
    borderColor: "#C7D2FE",
    padding: 16,
    marginTop: 16,
    gap: 8,
  },
  shieldHeader: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 8,
  },
  shieldTitle: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: "#4338CA",
  },
  shieldDetail: {
    fontSize: 13,
    color: "#4338CA",
    lineHeight: 18,
  },
  shieldStat: {
    fontSize: 12,
    color: "#6366F1",
    fontWeight: "600" as const,
  },
  shieldButton: {
    backgroundColor: "#6366F1",
    borderRadius: 12,
    paddingVertical: 12,
    alignItems: "center" as const,
    marginTop: 4,
  },
  shieldButtonText: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: "#fff",
  },
  shieldFootnote: {
    fontSize: 11,
    color: "#6366F1",
    opacity: 0.8,
  },
  sectionTitle: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginTop: 24,
    marginBottom: 12,
  },
  list: {
    gap: 8,
  },
  billRow: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 10,
    backgroundColor: Colors.dark.surface,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 12,
  },
  billInfo: {
    flex: 1,
  },
  billNote: {
    fontSize: 13,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  billDate: {
    fontSize: 11,
    color: Colors.dark.textTertiary,
    marginTop: 2,
  },
  billAmount: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  actionButton: {
    backgroundColor: Colors.dark.primary,
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: "center" as const,
    marginTop: 24,
  },
  actionButtonText: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.background,
  },
});
