import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useState } from "react";
import { Modal, Pressable, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Stack } from "expo-router";
import { CalendarClock, Plus, Repeat, Trash2, X } from "lucide-react-native";

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

type Delay = "1 minute" | "Tomorrow" | "Next week" | "1st of next month";

const DELAY_OPTIONS: { key: Delay; ms: number }[] = [
  { key: "1 minute", ms: 60 * 1000 },
  { key: "Tomorrow", ms: 24 * 60 * 60 * 1000 },
  { key: "Next week", ms: 7 * 24 * 60 * 60 * 1000 },
  { key: "1st of next month", ms: 30 * 24 * 60 * 60 * 1000 },
];

// Scheduled Sends - set up a payment now and let it fire on its own later.
// This is the person-to-person version (rent to a roommate, allowance to a
// kid, a reminder payment); for backend-backed recurring billing see the
// separate Recurring Payments screen instead.
export default function ScheduledSendsScreen() {
  const insets = useSafeAreaInsets();
  const { isDemoMode } = useAuth();
  const scheduledSends = useDemoLedger((s) => s.scheduledSends);
  const scheduleSend = useDemoLedger((s) => s.scheduleSend);
  const cancelScheduledSend = useDemoLedger((s) => s.cancelScheduledSend);

  const [showCreate, setShowCreate] = useState(false);
  const [toName, setToName] = useState("");
  const [amount, setAmount] = useState("");
  const [note, setNote] = useState("");
  const [delay, setDelay] = useState<Delay>("Tomorrow");
  const [repeatMonthly, setRepeatMonthly] = useState(false);

  const active = scheduledSends.filter((s) => !s.cancelled);
  const past = scheduledSends.filter((s) => s.cancelled && s.lastRunAt);

  const resetForm = () => {
    setToName("");
    setAmount("");
    setNote("");
    setDelay("Tomorrow");
    setRepeatMonthly(false);
  };

  const handleCreate = () => {
    const value = parseFloat(amount);
    if (!toName.trim() || isNaN(value) || value <= 0) {
      showAlert("Missing details", "Add who it's going to and a valid amount.");
      return;
    }
    const chosen = DELAY_OPTIONS.find((d) => d.key === delay)!;
    scheduleSend({
      toName: toName.trim(),
      amount: value,
      note: note.trim() || undefined,
      runAt: new Date(Date.now() + chosen.ms),
      repeatMonthly,
    });
    setShowCreate(false);
    resetForm();
  };

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

      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
        {!isDemoMode && (
          <View style={styles.modeNotice}>
            <Text style={styles.modeNoticeText}>
              Scheduled Sends runs on simulated time in demo mode. Try the demo account to see one fire automatically.
            </Text>
          </View>
        )}

        {active.length === 0 ? (
          <View style={styles.emptyState}>
            <CalendarClock color={Colors.dark.textTertiary} size={56} />
            <Text style={styles.emptyTitle}>Nothing scheduled</Text>
            <Text style={styles.emptyText}>
              Queue up rent, allowance, or any payment you'd rather not have to remember.
            </Text>
          </View>
        ) : (
          active.map((item) => (
            <View key={item.id} style={styles.scheduleCard}>
              <View style={styles.scheduleInfo}>
                <Text style={styles.scheduleName}>{item.toName}</Text>
                {item.note && <Text style={styles.scheduleNote}>{item.note}</Text>}
                <View style={styles.scheduleMetaRow}>
                  <Text style={styles.scheduleMeta}>
                    {item.runAt.toLocaleDateString("en-US", { month: "short", day: "numeric" })} at{" "}
                    {item.runAt.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" })}
                  </Text>
                  {item.repeatMonthly && (
                    <View style={styles.repeatBadge}>
                      <Repeat color={Colors.dark.primary} size={11} />
                      <Text style={styles.repeatBadgeText}>Monthly</Text>
                    </View>
                  )}
                </View>
              </View>
              <View style={styles.scheduleRight}>
                <Text style={styles.scheduleAmount}>${item.amount.toFixed(2)}</Text>
                <TouchableOpacity onPress={() => cancelScheduledSend(item.id)} hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
                  <Trash2 color={Colors.dark.error} size={16} />
                </TouchableOpacity>
              </View>
            </View>
          ))
        )}

        {past.length > 0 && (
          <>
            <Text style={styles.sectionTitle}>Already sent</Text>
            {past.map((item) => (
              <View key={item.id} style={styles.pastRow}>
                <Text style={styles.pastName}>{item.toName}</Text>
                <Text style={styles.pastAmount}>${item.amount.toFixed(2)}</Text>
              </View>
            ))}
          </>
        )}
      </ScrollView>

      <TouchableOpacity style={styles.fab} onPress={() => setShowCreate(true)} activeOpacity={0.85}>
        <Plus color="#FFFFFF" size={22} />
      </TouchableOpacity>

      <Modal visible={showCreate} transparent animationType="fade" onRequestClose={() => setShowCreate(false)}>
        <Pressable style={styles.backdrop} onPress={() => setShowCreate(false)}>
          <Pressable style={styles.modalCard} onPress={(e) => e.stopPropagation()}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Schedule a Send</Text>
              <TouchableOpacity onPress={() => setShowCreate(false)}>
                <X color={Colors.dark.textSecondary} size={22} />
              </TouchableOpacity>
            </View>

            <ScrollView keyboardShouldPersistTaps="handled">
              <Text style={styles.fieldLabel}>To</Text>
              <TextInput
                style={styles.input}
                value={toName}
                onChangeText={setToName}
                placeholder="Landlord, roommate, kid..."
                placeholderTextColor={Colors.dark.textTertiary}
              />

              <Text style={styles.fieldLabel}>Amount</Text>
              <TextInput
                style={styles.input}
                value={amount}
                onChangeText={(t) => setAmount(t.replace(/[^0-9.]/g, ""))}
                placeholder="0.00"
                placeholderTextColor={Colors.dark.textTertiary}
                keyboardType="decimal-pad"
              />

              <Text style={styles.fieldLabel}>Note (optional)</Text>
              <TextInput
                style={styles.input}
                value={note}
                onChangeText={setNote}
                placeholder="Rent for the month"
                placeholderTextColor={Colors.dark.textTertiary}
              />

              <Text style={styles.fieldLabel}>Send</Text>
              <View style={styles.delayRow}>
                {DELAY_OPTIONS.map((d) => (
                  <TouchableOpacity
                    key={d.key}
                    style={[styles.delayChip, delay === d.key && styles.delayChipActive]}
                    onPress={() => setDelay(d.key)}
                  >
                    <Text style={[styles.delayChipText, delay === d.key && styles.delayChipTextActive]}>
                      {d.key}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>

              <TouchableOpacity
                style={styles.repeatToggle}
                onPress={() => setRepeatMonthly(!repeatMonthly)}
                activeOpacity={0.8}
              >
                <Repeat color={repeatMonthly ? Colors.dark.primary : Colors.dark.textSecondary} size={18} />
                <Text style={styles.repeatToggleText}>Repeat monthly</Text>
                <View style={[styles.checkbox, repeatMonthly && styles.checkboxActive]}>
                  {repeatMonthly && <View style={styles.checkboxDot} />}
                </View>
              </TouchableOpacity>

              <TouchableOpacity style={styles.submitButton} onPress={handleCreate} activeOpacity={0.85}>
                <Text style={styles.submitButtonText}>Schedule It</Text>
              </TouchableOpacity>
            </ScrollView>
          </Pressable>
        </Pressable>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  content: {
    padding: 20,
    paddingBottom: 80,
  },
  modeNotice: {
    backgroundColor: `${Colors.dark.warning}14`,
    borderWidth: 1,
    borderColor: `${Colors.dark.warning}40`,
    borderRadius: 12,
    padding: 12,
    marginBottom: 16,
  },
  modeNoticeText: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    lineHeight: 17,
  },
  emptyState: {
    alignItems: "center" as const,
    paddingTop: 60,
    gap: 12,
    paddingHorizontal: 10,
  },
  emptyTitle: {
    fontSize: 17,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  emptyText: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 20,
  },
  scheduleCard: {
    flexDirection: "row" as const,
    justifyContent: "space-between",
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
    marginBottom: 10,
  },
  scheduleInfo: {
    flex: 1,
  },
  scheduleName: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  scheduleNote: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  scheduleMetaRow: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 8,
    marginTop: 6,
  },
  scheduleMeta: {
    fontSize: 11,
    color: Colors.dark.textTertiary,
  },
  repeatBadge: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 3,
    backgroundColor: `${Colors.dark.primary}14`,
    paddingHorizontal: 6,
    paddingVertical: 2,
    borderRadius: 6,
  },
  repeatBadgeText: {
    fontSize: 10,
    fontWeight: "700" as const,
    color: Colors.dark.primary,
  },
  scheduleRight: {
    alignItems: "flex-end" as const,
    gap: 10,
  },
  scheduleAmount: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  sectionTitle: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginTop: 20,
    marginBottom: 10,
  },
  pastRow: {
    flexDirection: "row" as const,
    justifyContent: "space-between",
    paddingVertical: 8,
  },
  pastName: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
  },
  pastAmount: {
    fontSize: 13,
    color: Colors.dark.textTertiary,
  },
  fab: {
    position: "absolute" as const,
    right: 20,
    bottom: 28,
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: Colors.dark.primary,
    alignItems: "center" as const,
    justifyContent: "center" as const,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 6,
  },
  backdrop: {
    flex: 1,
    backgroundColor: "rgba(0,0,0,0.5)",
    justifyContent: "center" as const,
    padding: 20,
  },
  modalCard: {
    backgroundColor: Colors.dark.background,
    borderRadius: 20,
    padding: 24,
    maxHeight: "85%",
  },
  modalHeader: {
    flexDirection: "row" as const,
    justifyContent: "space-between",
    alignItems: "center" as const,
    marginBottom: 16,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  fieldLabel: {
    fontSize: 12,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
    textTransform: "uppercase" as const,
    letterSpacing: 0.5,
    marginBottom: 8,
    marginTop: 14,
  },
  input: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    paddingHorizontal: 14,
    paddingVertical: 12,
    fontSize: 15,
    color: Colors.dark.text,
  },
  delayRow: {
    flexDirection: "row" as const,
    flexWrap: "wrap" as const,
    gap: 8,
  },
  delayChip: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    backgroundColor: Colors.dark.surfaceElevated,
  },
  delayChipActive: {
    borderColor: Colors.dark.primary,
    backgroundColor: `${Colors.dark.primary}1A`,
  },
  delayChipText: {
    fontSize: 12,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  delayChipTextActive: {
    color: Colors.dark.primary,
  },
  repeatToggle: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 10,
    marginTop: 18,
  },
  repeatToggleText: {
    flex: 1,
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  checkbox: {
    width: 22,
    height: 22,
    borderRadius: 6,
    borderWidth: 2,
    borderColor: Colors.dark.border,
    alignItems: "center" as const,
    justifyContent: "center" as const,
  },
  checkboxActive: {
    borderColor: Colors.dark.primary,
  },
  checkboxDot: {
    width: 12,
    height: 12,
    borderRadius: 3,
    backgroundColor: Colors.dark.primary,
  },
  submitButton: {
    backgroundColor: Colors.dark.primary,
    paddingVertical: 16,
    borderRadius: 14,
    alignItems: "center" as const,
    marginTop: 22,
    marginBottom: 4,
  },
  submitButtonText: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: "#FFFFFF",
  },
});
