import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useRouter, Stack } from "expo-router";
import {
  ChevronLeft,
  TrendingUp,
  Calendar,
  MapPin,
  Zap,
  Clock,
  ArrowUpRight,
  Target,
  AlertCircle,
  CheckCircle2,
  BarChart3,
  DollarSign,
  Sparkles,
} from "lucide-react-native";
import Colors from "@/constants/colors";
import { useAuth } from "@/lib/auth-context";

const BAR_MAX = 260;

const INCOME_WEEKS = [
  { week: "W1", amount: 980, projected: false },
  { week: "W2", amount: 1240, projected: false },
  { week: "W3", amount: 760, projected: false },
  { week: "W4", amount: 1100, projected: false },
  { week: "W5", amount: 1380, projected: true },
  { week: "W6", amount: 1150, projected: true },
  { week: "W7", amount: 1290, projected: true },
  { week: "W8", amount: 1450, projected: true },
];

const MAX_INCOME = Math.max(...INCOME_WEEKS.map((w) => w.amount));

const INCOME_SIGNALS = [
  {
    icon: MapPin,
    label: "Location signal",
    detail: "Higher gig demand in your area next week (+18%)",
    confidence: 87,
    color: "#6366F1",
  },
  {
    icon: Calendar,
    label: "Seasonal pattern",
    detail: "You historically earn 22% more in this month",
    confidence: 94,
    color: Colors.dark.success,
  },
  {
    icon: Clock,
    label: "Behavioral pattern",
    detail: "Your deposit frequency suggests a payout this Thursday",
    confidence: 91,
    color: "#F59E0B",
  },
  {
    icon: BarChart3,
    label: "Historical deposits",
    detail: "Average weekly income trending up $120 over 3 months",
    confidence: 88,
    color: Colors.dark.primary,
  },
];

const EARLY_ACCESS = [
  { label: "Advance up to", value: "$400", sub: "Based on predicted income", enabled: true },
  { label: "Dynamic limit", value: "$600", sub: "Unlocked at 90% confidence", enabled: false },
  { label: "Premium forecast", value: "90-day", sub: "Extended income outlook", enabled: true },
];

export default function PredictiveIncomeScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { isDemoMode } = useAuth();
  const [selectedWeek, setSelectedWeek] = useState<number | null>(null);

  const projectedAvg = Math.round(
    INCOME_WEEKS.filter((w) => w.projected).reduce((sum, w) => sum + w.amount, 0) /
      INCOME_WEEKS.filter((w) => w.projected).length
  );

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ headerShown: false }} />
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backBtn}>
          <ChevronLeft size={22} color={Colors.dark.text} />
        </TouchableOpacity>
        <View style={styles.headerCenter}>
          <TrendingUp size={18} color={Colors.dark.primary} />
          <Text style={styles.headerTitle}>Income Engine</Text>
        </View>
        <View style={[styles.engBadge]}>
          <Sparkles size={12} color="#6366F1" />
          <Text style={styles.engBadgeText}>Predictive</Text>
        </View>
      </View>

      <ScrollView
        style={styles.scroll}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: insets.bottom + 32 }]}
        showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}
      >
        {/* Hero */}
        <View style={styles.heroCard}>
          <Text style={styles.heroLabel}>Predicted monthly income</Text>
          <Text style={styles.heroAmount}>${(projectedAvg * 4).toLocaleString()}</Text>
          <View style={styles.heroMeta}>
            <View style={styles.heroBadge}>
              <CheckCircle2 size={13} color="#10B981" />
              <Text style={styles.heroBadgeText}>89% confidence</Text>
            </View>
            <Text style={styles.heroSub}>Based on behavior, location & history</Text>
          </View>
          <View style={styles.heroStats}>
            <View style={styles.heroStat}>
              <Text style={styles.heroStatValue}>${projectedAvg}</Text>
              <Text style={styles.heroStatLabel}>Avg/week (proj.)</Text>
            </View>
            <View style={styles.heroStatDiv} />
            <View style={styles.heroStat}>
              <Text style={styles.heroStatValue}>+14%</Text>
              <Text style={styles.heroStatLabel}>vs last month</Text>
            </View>
            <View style={styles.heroStatDiv} />
            <View style={styles.heroStat}>
              <Text style={styles.heroStatValue}>Thu</Text>
              <Text style={styles.heroStatLabel}>Next payout</Text>
            </View>
          </View>
        </View>

        {/* Chart */}
        <View style={styles.chartCard}>
          <View style={styles.chartHeader}>
            <Text style={styles.chartTitle}>8-Week Income Forecast</Text>
            <View style={styles.chartLegend}>
              <View style={styles.legendItem}>
                <View style={[styles.legendDot, { backgroundColor: Colors.dark.primary }]} />
                <Text style={styles.legendText}>Actual</Text>
              </View>
              <View style={styles.legendItem}>
                <View style={[styles.legendDot, { backgroundColor: "#6366F1", opacity: 0.5 }]} />
                <Text style={styles.legendText}>Projected</Text>
              </View>
            </View>
          </View>
          <View style={styles.chart}>
            {INCOME_WEEKS.map((w, i) => {
              const barH = Math.round((w.amount / MAX_INCOME) * BAR_MAX * 0.75);
              const isSelected = selectedWeek === i;
              return (
                <TouchableOpacity
                  key={i}
                  style={styles.barWrapper}
                  onPress={() => setSelectedWeek(isSelected ? null : i)}
                  activeOpacity={0.7}
                >
                  {isSelected && (
                    <View style={styles.barTooltip}>
                      <Text style={styles.barTooltipText}>${w.amount.toLocaleString()}</Text>
                    </View>
                  )}
                  <View
                    style={[
                      styles.bar,
                      {
                        height: barH,
                        backgroundColor: w.projected
                          ? isSelected ? "#6366F1" : "#6366F180"
                          : isSelected ? Colors.dark.primary : `${Colors.dark.primary}CC`,
                        borderStyle: w.projected ? "dashed" : "solid",
                      },
                    ]}
                  />
                  <Text style={[styles.barLabel, w.projected && styles.barLabelProjected]}>{w.week}</Text>
                </TouchableOpacity>
              );
            })}
          </View>
        </View>

        {/* Signals */}
        <View style={styles.sectionHeader}>
          <Target size={15} color={Colors.dark.primary} />
          <Text style={styles.sectionTitle}>Prediction Signals</Text>
        </View>

        {INCOME_SIGNALS.map((s, i) => {
          const Icon = s.icon;
          return (
            <View key={i} style={styles.signalCard}>
              <View style={[styles.signalIcon, { backgroundColor: `${s.color}15` }]}>
                <Icon size={18} color={s.color} />
              </View>
              <View style={styles.signalBody}>
                <Text style={styles.signalLabel}>{s.label}</Text>
                <Text style={styles.signalDetail}>{s.detail}</Text>
              </View>
              <View style={styles.signalConf}>
                <Text style={[styles.signalConfValue, { color: s.color }]}>{s.confidence}%</Text>
                <Text style={styles.signalConfLabel}>conf.</Text>
              </View>
            </View>
          );
        })}

        {/* Early Access */}
        <View style={[styles.sectionHeader, { marginTop: 4 }]}>
          <Zap size={15} color="#F59E0B" />
          <Text style={styles.sectionTitle}>Early-Access Features</Text>
        </View>

        {EARLY_ACCESS.map((item, i) => (
          <View key={i} style={[styles.earlyCard, !item.enabled && styles.earlyCardLocked]}>
            <View style={styles.earlyLeft}>
              <Text style={[styles.earlyValue, !item.enabled && styles.earlyValueLocked]}>{item.value}</Text>
              <Text style={styles.earlyLabel}>{item.label}</Text>
              <Text style={styles.earlySub}>{item.sub}</Text>
            </View>
            {item.enabled ? (
              <TouchableOpacity style={styles.earlyBtn}>
                <Text style={styles.earlyBtnText}>Access</Text>
                <ArrowUpRight size={13} color={Colors.dark.primary} />
              </TouchableOpacity>
            ) : (
              <View style={styles.earlyLocked}>
                <AlertCircle size={14} color={Colors.dark.textTertiary} />
                <Text style={styles.earlyLockedText}>Locked</Text>
              </View>
            )}
          </View>
        ))}

        {/* How it works */}
        <View style={styles.howCard}>
          <View style={styles.howHeader}>
            <DollarSign size={16} color={Colors.dark.primary} />
            <Text style={styles.howTitle}>How the engine works</Text>
          </View>
          <Text style={styles.howBody}>
            The Predictive Income Engine analyzes your deposit history, location signals, behavioral patterns, and seasonal data to forecast your income up to 90 days ahead. Gig workers, freelancers, and hourly employees with irregular income benefit most - it smooths uncertainty and unlocks features tied to predicted cash flow.
          </Text>
        </View>

        {isDemoMode && (
          <View style={styles.demoBanner}>
            <Text style={styles.demoBannerText}>
              📊 Demo: Predictions based on simulated 6-month behavioral data
            </Text>
          </View>
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.dark.background },
  header: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingHorizontal: 20, paddingVertical: 14, borderBottomWidth: 1, borderBottomColor: Colors.dark.border },
  backBtn: { width: 36, height: 36, borderRadius: 18, backgroundColor: Colors.dark.surface, alignItems: "center", justifyContent: "center" },
  headerCenter: { flexDirection: "row", alignItems: "center", gap: 6 },
  headerTitle: { fontSize: 18, fontWeight: "700", color: Colors.dark.text },
  engBadge: { flexDirection: "row", alignItems: "center", gap: 4, backgroundColor: "#EEF2FF", paddingHorizontal: 10, paddingVertical: 5, borderRadius: 12 },
  engBadgeText: { fontSize: 12, fontWeight: "600", color: "#6366F1" },
  scroll: { flex: 1 },
  scrollContent: { padding: 20, gap: 14 },
  heroCard: { backgroundColor: Colors.dark.primary, borderRadius: 22, padding: 24, gap: 10 },
  heroLabel: { fontSize: 13, color: "rgba(255,255,255,0.6)", fontWeight: "500" },
  heroAmount: { fontSize: 42, fontWeight: "800", color: "#fff", letterSpacing: -1 },
  heroMeta: { flexDirection: "row", alignItems: "center", gap: 10 },
  heroBadge: { flexDirection: "row", alignItems: "center", gap: 5, backgroundColor: "rgba(16,185,129,0.2)", paddingHorizontal: 10, paddingVertical: 4, borderRadius: 10 },
  heroBadgeText: { fontSize: 12, fontWeight: "600", color: "#34D399" },
  heroSub: { fontSize: 12, color: "rgba(255,255,255,0.5)" },
  heroStats: { flexDirection: "row", alignItems: "center", paddingTop: 12, borderTopWidth: 1, borderTopColor: "rgba(255,255,255,0.15)", marginTop: 6 },
  heroStat: { flex: 1, alignItems: "center" },
  heroStatValue: { fontSize: 20, fontWeight: "800", color: "#fff" },
  heroStatLabel: { fontSize: 10, color: "rgba(255,255,255,0.55)", marginTop: 2, textAlign: "center" },
  heroStatDiv: { width: 1, height: 32, backgroundColor: "rgba(255,255,255,0.15)" },
  chartCard: { backgroundColor: Colors.dark.surface, borderRadius: 18, padding: 18, gap: 14, borderWidth: 1, borderColor: Colors.dark.border },
  chartHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
  chartTitle: { fontSize: 14, fontWeight: "700", color: Colors.dark.text },
  chartLegend: { flexDirection: "row", gap: 12 },
  legendItem: { flexDirection: "row", alignItems: "center", gap: 5 },
  legendDot: { width: 8, height: 8, borderRadius: 4 },
  legendText: { fontSize: 11, color: Colors.dark.textSecondary },
  chart: { flexDirection: "row", alignItems: "flex-end", gap: 6, height: 120 },
  barWrapper: { flex: 1, alignItems: "center", gap: 4, position: "relative" },
  barTooltip: { position: "absolute", top: -28, backgroundColor: Colors.dark.primary, borderRadius: 6, paddingHorizontal: 6, paddingVertical: 3, zIndex: 10 },
  barTooltipText: { fontSize: 10, fontWeight: "700", color: "#fff" },
  bar: { width: "100%", borderRadius: 5, minHeight: 4 },
  barLabel: { fontSize: 10, color: Colors.dark.textSecondary, fontWeight: "500" },
  barLabelProjected: { color: "#6366F1" },
  sectionHeader: { flexDirection: "row", alignItems: "center", gap: 7, marginBottom: 2 },
  sectionTitle: { fontSize: 15, fontWeight: "700", color: Colors.dark.text },
  signalCard: { flexDirection: "row", alignItems: "center", gap: 12, backgroundColor: Colors.dark.surface, borderRadius: 14, padding: 14, borderWidth: 1, borderColor: Colors.dark.border },
  signalIcon: { width: 38, height: 38, borderRadius: 11, alignItems: "center", justifyContent: "center", flexShrink: 0 },
  signalBody: { flex: 1, gap: 3 },
  signalLabel: { fontSize: 13, fontWeight: "600", color: Colors.dark.text },
  signalDetail: { fontSize: 12, color: Colors.dark.textSecondary, lineHeight: 16 },
  signalConf: { alignItems: "center" },
  signalConfValue: { fontSize: 16, fontWeight: "800" },
  signalConfLabel: { fontSize: 10, color: Colors.dark.textTertiary },
  earlyCard: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", backgroundColor: Colors.dark.surface, borderRadius: 14, padding: 16, borderWidth: 1, borderColor: Colors.dark.border },
  earlyCardLocked: { opacity: 0.5 },
  earlyLeft: { gap: 2 },
  earlyValue: { fontSize: 22, fontWeight: "800", color: Colors.dark.primary },
  earlyValueLocked: { color: Colors.dark.textTertiary },
  earlyLabel: { fontSize: 13, fontWeight: "600", color: Colors.dark.text },
  earlySub: { fontSize: 11, color: Colors.dark.textSecondary },
  earlyBtn: { flexDirection: "row", alignItems: "center", gap: 4, backgroundColor: `${Colors.dark.primary}10`, paddingHorizontal: 12, paddingVertical: 8, borderRadius: 10 },
  earlyBtnText: { fontSize: 13, fontWeight: "600", color: Colors.dark.primary },
  earlyLocked: { flexDirection: "row", alignItems: "center", gap: 4 },
  earlyLockedText: { fontSize: 12, color: Colors.dark.textTertiary },
  howCard: { backgroundColor: Colors.dark.surface, borderRadius: 16, padding: 16, gap: 10, borderWidth: 1, borderColor: Colors.dark.border },
  howHeader: { flexDirection: "row", alignItems: "center", gap: 8 },
  howTitle: { fontSize: 14, fontWeight: "700", color: Colors.dark.text },
  howBody: { fontSize: 13, color: Colors.dark.textSecondary, lineHeight: 20 },
  demoBanner: { backgroundColor: `${Colors.dark.primary}10`, borderRadius: 12, padding: 14 },
  demoBannerText: { fontSize: 13, color: Colors.dark.primary, textAlign: "center", fontWeight: "500" },
});
