import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Modal,
  ActivityIndicator,
  Platform,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useRouter, Stack } from "expo-router";
import {
  ChevronLeft,
  Zap,
  Plus,
  X,
  Sparkles,
  ShieldCheck,
  Pause,
  Play,
  Trash2,
} 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";

const TRIGGER_OPTIONS: { value: string; label: string }[] = [
  { value: "balance_threshold", label: "Balance crosses a threshold" },
  { value: "scheduled", label: "On a schedule" },
  { value: "incoming_payment", label: "When money comes in" },
  { value: "round_up", label: "Round up every purchase" },
  { value: "goal_progress", label: "Savings goal progress" },
  { value: "spending_pattern", label: "Spending pattern detected" },
];

const ACTION_OPTIONS: { value: string; label: string }[] = [
  { value: "auto_save", label: "Auto-save to savings" },
  { value: "auto_transfer", label: "Auto-transfer to contact" },
  { value: "auto_invest", label: "Auto-invest" },
  { value: "round_up_invest", label: "Invest the round-up" },
  { value: "smart_alert", label: "Just alert me (no money moves)" },
];

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

  const [showCreateRule, setShowCreateRule] = useState(false);
  const [ruleName, setRuleName] = useState("");
  const [trigger, setTrigger] = useState(TRIGGER_OPTIONS[0].value);
  const [action, setAction] = useState(ACTION_OPTIONS[0].value);
  const [thresholdAmount, setThresholdAmount] = useState("");

  const bundleQuery = trpc.automation.myBundle.useQuery(undefined, { enabled: !isDemoMode });
  const catalogQuery = trpc.automation.listBundles.useQuery(undefined, { enabled: !isDemoMode });
  const rulesQuery = trpc.automation.listRules.useQuery(undefined, { enabled: !isDemoMode });

  const subscribeMutation = trpc.automation.subscribeBundle.useMutation({
    onSuccess: () => {
      bundleQuery.refetch();
      showAlert("Automation Activated", "Your bundle is live. You can start creating money rules.");
    },
    onError: () => showAlert("Couldn't Subscribe", "Failed to subscribe to automation."),
  });

  const cancelBundleMutation = trpc.automation.cancelBundle.useMutation({
    onSuccess: () => {
      bundleQuery.refetch();
      showAlert("Cancelled", "Your automation bundle won't renew next period.");
    },
    onError: () => showAlert("Error", "Failed to update automation."),
  });

  const createRuleMutation = trpc.automation.createRule.useMutation({
    onSuccess: () => {
      rulesQuery.refetch();
      setShowCreateRule(false);
      setRuleName("");
      setThresholdAmount("");
      showAlert("Rule Created", "Your money rule is active and running privately on your account.");
    },
    onError: () => showAlert("Couldn't Create Rule", "Failed to create automation rule."),
  });

  const setRuleStatusMutation = trpc.automation.setRuleStatus.useMutation({
    onSuccess: () => rulesQuery.refetch(),
    onError: () => showAlert("Error", "Failed to delete automation rule."),
  });

  const bundle = bundleQuery.data;
  const catalog = catalogQuery.data || [];
  const rules = rulesQuery.data || [];

  const handleCreateRule = () => {
    if (!ruleName.trim()) {
      showAlert("Name Required", "Give your rule a short name.");
      return;
    }
    createRuleMutation.mutate({
      name: ruleName.trim(),
      trigger: trigger as any,
      triggerConfig: thresholdAmount ? { amount: parseFloat(thresholdAmount) } : {},
      action: action as any,
      actionConfig: {},
    });
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ headerShown: false }} />
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <ChevronLeft color={Colors.dark.text} size={24} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Smart Automation</Text>
        <View style={{ width: 40 }} />
      </View>

      <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
        <View style={styles.heroCard}>
          <Sparkles color={Colors.dark.warning} size={28} />
          <Text style={styles.heroTitle}>Your money, run by rules</Text>
          <Text style={styles.heroSubtitle}>
            AI-driven flows that save, move, and protect money for you. Rules run privately on
            your account - nobody else ever sees your conditions or triggers.
          </Text>
        </View>

        {isDemoMode ? (
          <View style={styles.demoNotice}>
            <Text style={styles.demoNoticeText}>
              Smart Automation needs a live account - switch off demo mode to subscribe and
              create rules.
            </Text>
          </View>
        ) : (
          <>
            <View style={styles.section}>
              <Text style={styles.sectionLabel}>Automation Plan</Text>

              {bundleQuery.isLoading ? (
                <ActivityIndicator color={Colors.dark.primary} />
              ) : bundle ? (
                <View style={styles.activeBundleCard}>
                  <View style={styles.activeBundleRow}>
                    <Zap color={Colors.dark.warning} size={20} />
                    <Text style={styles.activeBundleTier}>{bundle.tier.toUpperCase()}</Text>
                  </View>
                  <Text style={styles.activeBundlePrice}>
                    ${bundle.monthlyPrice.toFixed(2)}/mo
                  </Text>
                  <Text style={styles.activeBundleMeta}>
                    Renews {new Date(bundle.currentPeriodEnd).toLocaleDateString()}
                    {bundle.cancelAtPeriodEnd ? " · cancels at period end" : ""}
                  </Text>
                  {!bundle.cancelAtPeriodEnd && (
                    <TouchableOpacity
                      style={styles.cancelLink}
                      onPress={() => cancelBundleMutation.mutate()}
                    >
                      <Text style={styles.cancelLinkText}>Cancel renewal</Text>
                    </TouchableOpacity>
                  )}
                </View>
              ) : (
                catalog.map((b) => (
                  <View key={b.tier} style={styles.bundleCard}>
                    <View style={styles.bundleCardHeader}>
                      <Text style={styles.bundleName}>{b.name}</Text>
                      <Text style={styles.bundlePrice}>${b.monthlyPrice.toFixed(2)}/mo</Text>
                    </View>
                    <Text style={styles.bundleDescription}>{b.description}</Text>
                    <Text style={styles.bundleMeta}>
                      Up to {b.ruleLimit >= 9999 ? "unlimited" : b.ruleLimit} rules · $
                      {b.microFeePerTrigger.toFixed(3)} per trigger
                    </Text>
                    <TouchableOpacity
                      style={styles.subscribeButton}
                      onPress={() => subscribeMutation.mutate({ tier: b.tier as any })}
                      disabled={subscribeMutation.isPending}
                    >
                      <Text style={styles.subscribeButtonText}>
                        {subscribeMutation.isPending ? "Subscribing..." : "Subscribe"}
                      </Text>
                    </TouchableOpacity>
                  </View>
                ))
              )}
            </View>

            <View style={styles.section}>
              <View style={styles.sectionHeaderRow}>
                <Text style={styles.sectionLabel}>Money Rules</Text>
                <TouchableOpacity
                  onPress={() => setShowCreateRule(true)}
                  style={styles.addRuleButton}
                  disabled={!bundle}
                >
                  <Plus color={bundle ? Colors.dark.primary : Colors.dark.subtext} size={18} />
                </TouchableOpacity>
              </View>

              {!bundle && (
                <Text style={styles.helperText}>Subscribe to a plan above to create rules.</Text>
              )}

              {rulesQuery.isLoading ? (
                <ActivityIndicator color={Colors.dark.primary} />
              ) : rules.length === 0 && bundle ? (
                <Text style={styles.helperText}>No rules yet. Tap + to create your first one.</Text>
              ) : (
                rules.map((rule) => (
                  <View key={rule.id} style={styles.ruleCard}>
                    <View style={styles.ruleCardTop}>
                      <Text style={styles.ruleName}>{rule.name}</Text>
                      <View style={styles.ruleActions}>
                        <TouchableOpacity
                          onPress={() =>
                            setRuleStatusMutation.mutate({
                              ruleId: rule.id,
                              status: rule.status === "active" ? "paused" : "active",
                            })
                          }
                        >
                          {rule.status === "active" ? (
                            <Pause color={Colors.dark.subtext} size={18} />
                          ) : (
                            <Play color={Colors.dark.primary} size={18} />
                          )}
                        </TouchableOpacity>
                        <TouchableOpacity
                          onPress={() =>
                            setRuleStatusMutation.mutate({ ruleId: rule.id, status: "deleted" })
                          }
                          style={{ marginLeft: 12 }}
                        >
                          <Trash2 color={Colors.dark.error} size={18} />
                        </TouchableOpacity>
                      </View>
                    </View>
                    <Text style={styles.ruleMeta}>
                      {TRIGGER_OPTIONS.find((t) => t.value === rule.trigger)?.label} →{" "}
                      {ACTION_OPTIONS.find((a) => a.value === rule.action)?.label}
                    </Text>
                    <Text style={styles.ruleStats}>
                      {rule.totalTriggers} triggers · ${rule.totalFeesPaid.toFixed(2)} in fees ·{" "}
                      {rule.status}
                    </Text>
                  </View>
                ))
              )}
            </View>

            <TouchableOpacity
              style={styles.escrowCallout}
              onPress={() => router.push("/escrow" as any)}
            >
              <ShieldCheck color={Colors.dark.primary} size={22} />
              <View style={{ flex: 1, marginLeft: 12 }}>
                <Text style={styles.escrowCalloutTitle}>Smart Escrow</Text>
                <Text style={styles.escrowCalloutText}>
                  AI-priced protection for risky transactions - 0.5%–1.5% of the amount based on
                  risk, released automatically by your rules.
                </Text>
              </View>
            </TouchableOpacity>
          </>
        )}
      </ScrollView>

      <Modal visible={showCreateRule} animationType="slide" transparent>
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>New Money Rule</Text>
              <TouchableOpacity onPress={() => setShowCreateRule(false)}>
                <X color={Colors.dark.text} size={24} />
              </TouchableOpacity>
            </View>

            <Text style={styles.inputLabel}>Name</Text>
            <TextInput
              style={styles.input}
              placeholder="e.g. Save my round-ups"
              placeholderTextColor={Colors.dark.subtext}
              value={ruleName}
              onChangeText={setRuleName}
            />

            <Text style={styles.inputLabel}>When</Text>
            <View style={styles.optionList}>
              {TRIGGER_OPTIONS.map((opt) => (
                <TouchableOpacity
                  key={opt.value}
                  style={[styles.optionPill, trigger === opt.value && styles.optionPillSelected]}
                  onPress={() => setTrigger(opt.value)}
                >
                  <Text
                    style={[
                      styles.optionPillText,
                      trigger === opt.value && styles.optionPillTextSelected,
                    ]}
                  >
                    {opt.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            {trigger === "balance_threshold" && (
              <>
                <Text style={styles.inputLabel}>Threshold amount</Text>
                <TextInput
                  style={styles.input}
                  placeholder="0.00"
                  placeholderTextColor={Colors.dark.subtext}
                  keyboardType="decimal-pad"
                  value={thresholdAmount}
                  onChangeText={setThresholdAmount}
                />
              </>
            )}

            <Text style={styles.inputLabel}>Then</Text>
            <View style={styles.optionList}>
              {ACTION_OPTIONS.map((opt) => (
                <TouchableOpacity
                  key={opt.value}
                  style={[styles.optionPill, action === opt.value && styles.optionPillSelected]}
                  onPress={() => setAction(opt.value)}
                >
                  <Text
                    style={[
                      styles.optionPillText,
                      action === opt.value && styles.optionPillTextSelected,
                    ]}
                  >
                    {opt.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            <TouchableOpacity
              style={styles.createButton}
              onPress={handleCreateRule}
              disabled={createRuleMutation.isPending}
            >
              <Text style={styles.createButtonText}>
                {createRuleMutation.isPending ? "Creating..." : "Create Rule"}
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.dark.background },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  backButton: { width: 40, height: 40, justifyContent: "center" },
  headerTitle: { fontSize: 17, fontWeight: "600", color: Colors.dark.text },
  scrollContent: { padding: 16, paddingBottom: 48 },
  heroCard: {
    backgroundColor: Colors.dark.card,
    borderRadius: 16,
    padding: 20,
    marginBottom: 20,
  },
  heroTitle: { fontSize: 20, fontWeight: "700", color: Colors.dark.text, marginTop: 10 },
  heroSubtitle: { fontSize: 14, color: Colors.dark.subtext, marginTop: 6, lineHeight: 20 },
  demoNotice: { backgroundColor: Colors.dark.card, borderRadius: 12, padding: 16 },
  demoNoticeText: { color: Colors.dark.subtext, fontSize: 14, lineHeight: 20 },
  section: { marginBottom: 24 },
  sectionLabel: { fontSize: 14, fontWeight: "600", color: Colors.dark.subtext, marginBottom: 10 },
  sectionHeaderRow: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginBottom: 10,
  },
  addRuleButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: Colors.dark.card,
    alignItems: "center",
    justifyContent: "center",
  },
  helperText: { color: Colors.dark.subtext, fontSize: 13 },
  bundleCard: {
    backgroundColor: Colors.dark.card,
    borderRadius: 14,
    padding: 16,
    marginBottom: 12,
  },
  bundleCardHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
  bundleName: { color: Colors.dark.text, fontSize: 16, fontWeight: "700" },
  bundlePrice: { color: Colors.dark.primary, fontSize: 16, fontWeight: "700" },
  bundleDescription: { color: Colors.dark.subtext, fontSize: 13, marginTop: 6 },
  bundleMeta: { color: Colors.dark.subtext, fontSize: 12, marginTop: 6, opacity: 0.8 },
  subscribeButton: {
    backgroundColor: Colors.dark.primary,
    borderRadius: 10,
    paddingVertical: 10,
    alignItems: "center",
    marginTop: 12,
  },
  subscribeButtonText: { color: "#fff", fontWeight: "600", fontSize: 14 },
  activeBundleCard: { backgroundColor: Colors.dark.card, borderRadius: 14, padding: 16 },
  activeBundleRow: { flexDirection: "row", alignItems: "center", gap: 8 },
  activeBundleTier: { color: Colors.dark.text, fontWeight: "700", fontSize: 16, marginLeft: 6 },
  activeBundlePrice: { color: Colors.dark.primary, fontSize: 22, fontWeight: "700", marginTop: 8 },
  activeBundleMeta: { color: Colors.dark.subtext, fontSize: 12, marginTop: 6 },
  cancelLink: { marginTop: 10 },
  cancelLinkText: { color: Colors.dark.error, fontSize: 13, fontWeight: "600" },
  ruleCard: { backgroundColor: Colors.dark.card, borderRadius: 14, padding: 14, marginBottom: 10 },
  ruleCardTop: { flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
  ruleName: { color: Colors.dark.text, fontSize: 15, fontWeight: "600" },
  ruleActions: { flexDirection: "row", alignItems: "center" },
  ruleMeta: { color: Colors.dark.subtext, fontSize: 12, marginTop: 6 },
  ruleStats: { color: Colors.dark.subtext, fontSize: 11, marginTop: 6, opacity: 0.7 },
  escrowCallout: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: Colors.dark.card,
    borderRadius: 14,
    padding: 16,
  },
  escrowCalloutTitle: { color: Colors.dark.text, fontSize: 15, fontWeight: "700" },
  escrowCalloutText: { color: Colors.dark.subtext, fontSize: 12, marginTop: 4, lineHeight: 17 },
  modalOverlay: { flex: 1, backgroundColor: "rgba(0,0,0,0.6)", justifyContent: "flex-end" },
  modalContent: {
    backgroundColor: Colors.dark.background,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 20,
    maxHeight: "85%",
  },
  modalHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 16,
  },
  modalTitle: { color: Colors.dark.text, fontSize: 18, fontWeight: "700" },
  inputLabel: { color: Colors.dark.subtext, fontSize: 13, fontWeight: "600", marginTop: 14, marginBottom: 6 },
  input: {
    backgroundColor: Colors.dark.card,
    borderRadius: 10,
    paddingHorizontal: 14,
    paddingVertical: Platform.OS === "ios" ? 12 : 8,
    color: Colors.dark.text,
    fontSize: 15,
  },
  optionList: { flexDirection: "row", flexWrap: "wrap", gap: 8 },
  optionPill: {
    backgroundColor: Colors.dark.card,
    borderRadius: 20,
    paddingHorizontal: 14,
    paddingVertical: 8,
  },
  optionPillSelected: { backgroundColor: Colors.dark.primary },
  optionPillText: { color: Colors.dark.subtext, fontSize: 13 },
  optionPillTextSelected: { color: "#fff", fontWeight: "600" },
  createButton: {
    backgroundColor: Colors.dark.primary,
    borderRadius: 12,
    paddingVertical: 14,
    alignItems: "center",
    marginTop: 22,
  },
  createButtonText: { color: "#fff", fontWeight: "700", fontSize: 15 },
});
