"use client";

import { useState, useRef, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  useRecurring,
  useCreateRecurring,
  useUpdateRecurring,
  useToggleRecurring,
  useSkipRecurring,
  useDeleteRecurring,
  type RecurringItem,
} from "@/hooks/use-recurring";
import { useBankAccounts } from "@/hooks/use-bank-accounts";
import { useCategories } from "@/hooks/use-categories";
import { recurringTransactionSchema, type RecurringTransactionInput } from "@/lib/validations/recurring";
import { formatCents } from "@/lib/utils/format";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import {
  Plus, RefreshCw, Pause, Play, SkipForward, Pencil, Trash2,
  CalendarClock, TrendingDown, TrendingUp, AlertCircle,
} from "lucide-react";
import { CategoryIcon } from "@/components/ui/category-icon";

// ── Helpers ──────────────────────────────────────────────────

const FREQ_LABEL: Record<string, string> = {
  DAILY: "Daily", WEEKLY: "Weekly", BIWEEKLY: "Biweekly",
  MONTHLY: "Monthly", QUARTERLY: "Quarterly", YEARLY: "Yearly",
};

const FREQ_COLOR: Record<string, string> = {
  DAILY: "bg-red-500/20 text-red-300",
  WEEKLY: "bg-amber-500/20 text-amber-300",
  BIWEEKLY: "bg-orange-500/20 text-orange-300",
  MONTHLY: "bg-blue-500/20 text-blue-300",
  QUARTERLY: "bg-violet-500/20 text-violet-300",
  YEARLY: "bg-emerald-500/20 text-emerald-300",
};

// Multipliers to normalise to monthly cost
const TO_MONTHLY: Record<string, number> = {
  DAILY: 30.44, WEEKLY: 4.33, BIWEEKLY: 2.17,
  MONTHLY: 1, QUARTERLY: 1 / 3, YEARLY: 1 / 12,
};

function monthlyEquiv(item: RecurringItem): number {
  return Math.round(item.amountCents * (TO_MONTHLY[item.frequency] ?? 1));
}

function todayStr() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

function dueDaysLabel(dateStr: string): { label: string; color: string } {
  const today = new Date(); today.setHours(0, 0, 0, 0);
  const due = new Date(dateStr); due.setHours(0, 0, 0, 0);
  const diff = Math.round((due.getTime() - today.getTime()) / 86_400_000);
  if (diff < 0)  return { label: "Overdue", color: "text-red-400" };
  if (diff === 0) return { label: "Today", color: "text-amber-400" };
  if (diff === 1) return { label: "Tomorrow", color: "text-amber-300" };
  if (diff <= 7)  return { label: `In ${diff} days`, color: "text-yellow-300" };
  const d = new Date(dateStr);
  return {
    label: d.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
    color: "text-slate-400",
  };
}

function accountIcon(type: string) {
  switch (type) {
    case "CASH":       return "💵";
    case "WALLET":     return "👛";
    case "CHECKING":   return "🏦";
    case "SAVINGS":    return "🏧";
    case "INVESTMENT": return "📈";
    default:           return "💳";
  }
}

const PRESET_ICONS = ["📺", "🎵", "☁️", "🎮", "📰", "🏋️", "🚗", "🏠", "💊", "📱", "🛒", "✈️", "🎓", "💼", "⚡", "🌐"];
const PRESET_COLORS = ["#10b981", "#3b82f6", "#8b5cf6", "#f59e0b", "#ef4444", "#06b6d4", "#ec4899", "#84cc16"];

// ── Add/Edit Sheet Form ───────────────────────────────────────

interface RecurringFormProps {
  open: boolean;
  onClose: () => void;
  existing?: RecurringItem | null;
}

function RecurringForm({ open, onClose, existing }: RecurringFormProps) {
  const { data: accounts = [] } = useBankAccounts();
  const { data: categories = [] } = useCategories();
  const createMutation = useCreateRecurring();
  const updateMutation = useUpdateRecurring();

  const [amountStr, setAmountStr] = useState("");
  const [selectedType, setSelectedType] = useState<"INCOME" | "EXPENSE">("EXPENSE");
  const [selectedFreq, setSelectedFreq] = useState<RecurringTransactionInput["frequency"]>("MONTHLY");
  const [selectedIcon, setSelectedIcon] = useState("📅");
  const [selectedColor, setSelectedColor] = useState("#10b981");
  const formInitialized = useRef(false);

  const {
    register, handleSubmit, setValue, watch, reset,
    formState: { errors, isSubmitting },
  } = useForm<RecurringTransactionInput>({
    resolver: zodResolver(recurringTransactionSchema),
    defaultValues: {
      type: "EXPENSE" as const,
      frequency: "MONTHLY" as const,
      currency: "USD",
      reminderDays: 0,
      startDate: todayStr(),
      amountCents: 0,
      bankAccountId: "",
      description: "",
    },
  });

  useEffect(() => {
    if (!open) { formInitialized.current = false; return; }
    if (formInitialized.current) return;
    formInitialized.current = true;

    if (existing) {
      const amt = (existing.amountCents / 100).toFixed(2);
      setAmountStr(amt);
      setSelectedType(existing.type);
      setSelectedFreq(existing.frequency);
      setSelectedIcon(existing.icon ?? "📅");
      setSelectedColor(existing.color ?? "#10b981");
      reset({
        type: existing.type,
        frequency: existing.frequency,
        bankAccountId: existing.bankAccountId,
        categoryId: existing.categoryId ?? undefined,
        amountCents: existing.amountCents,
        currency: existing.currency,
        description: existing.description,
        notes: existing.notes ?? undefined,
        startDate: existing.startDate.split("T")[0],
        endDate: existing.endDate ? existing.endDate.split("T")[0] : undefined,
        icon: existing.icon ?? undefined,
        color: existing.color ?? undefined,
        merchantName: existing.merchantName ?? undefined,
        billingUrl: existing.billingUrl ?? undefined,
        reminderDays: existing.reminderDays,
      });
    } else {
      setAmountStr("");
      setSelectedType("EXPENSE");
      setSelectedFreq("MONTHLY");
      setSelectedIcon("📅");
      setSelectedColor("#10b981");
      reset({
        type: "EXPENSE" as const,
        frequency: "MONTHLY" as const,
        currency: "USD",
        reminderDays: 0,
        startDate: todayStr(),
        amountCents: 0,
        bankAccountId: "",
        description: "",
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, existing]);

  const watchedAccount = watch("bankAccountId");
  const watchedCategory = watch("categoryId");
  const watchedStartDate = watch("startDate");
  const watchedEndDate = watch("endDate");
  const watchedReminderDays = watch("reminderDays");

  async function onSubmit(data: RecurringTransactionInput) {
    try {
      if (existing) {
        await updateMutation.mutateAsync({ id: existing.id, data });
      } else {
        await createMutation.mutateAsync(data);
      }
      onClose();
    } catch {
      // error surfaced via mutation state
    }
  }

  const expenseCategories = categories.filter((c) => c.type === "EXPENSE");
  const incomeCategories  = categories.filter((c) => c.type === "INCOME");
  const visibleCats = selectedType === "INCOME" ? incomeCategories : expenseCategories;

  const mutationError = createMutation.error ?? updateMutation.error;

  return (
    <Sheet open={open} onOpenChange={(v) => !v && onClose()}>
      <SheetContent
        side="bottom"
        className="bg-slate-900 border-slate-700 rounded-t-2xl p-0 max-h-[92vh] overflow-y-auto"
      >
        <SheetTitle className="sr-only">
          {existing ? "Edit Recurring" : "New Recurring Transaction"}
        </SheetTitle>

        <div className="sticky top-0 bg-slate-900 pt-4 pb-3 px-4 border-b border-slate-700/50 z-10">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-bold text-white">
              {existing ? "Edit Recurring" : "New Recurring"}
            </h2>
            <button onClick={onClose} className="text-slate-500 hover:text-slate-300 text-sm">Cancel</button>
          </div>
        </div>

        <form onSubmit={handleSubmit(onSubmit)} className="p-4 space-y-5 pb-8">

          {/* Type toggle */}
          <div className="flex gap-2">
            {(["EXPENSE", "INCOME"] as const).map((t) => (
              <button
                key={t}
                type="button"
                onClick={() => {
                  setSelectedType(t);
                  setValue("type", t);
                  setValue("categoryId", undefined);
                }}
                className={cn(
                  "flex-1 py-2 rounded-xl text-sm font-semibold transition-all",
                  selectedType === t
                    ? t === "EXPENSE"
                      ? "bg-red-500/20 text-red-300 ring-1 ring-red-500/50"
                      : "bg-emerald-500/20 text-emerald-300 ring-1 ring-emerald-500/50"
                    : "bg-slate-800 text-slate-400"
                )}
              >
                {t === "EXPENSE" ? "💸 Expense" : "💰 Income"}
              </button>
            ))}
          </div>

          {/* Icon + Amount */}
          <div className="flex items-center gap-3">
            <div className="relative">
              <button
                type="button"
                className="w-14 h-14 rounded-2xl flex items-center justify-center text-2xl border border-slate-700 bg-slate-800"
                onClick={() => {
                  const next = PRESET_ICONS[(PRESET_ICONS.indexOf(selectedIcon) + 1) % PRESET_ICONS.length];
                  setSelectedIcon(next);
                  setValue("icon", next);
                }}
              >
                {selectedIcon}
              </button>
            </div>
            <div className="flex-1">
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xl font-light">$</span>
                <input
                  type="number"
                  step="0.01"
                  min="0"
                  value={amountStr}
                  onChange={(e) => {
                    setAmountStr(e.target.value);
                    setValue("amountCents", Math.round(parseFloat(e.target.value || "0") * 100));
                  }}
                  placeholder="0.00"
                  className="w-full pl-8 pr-4 py-4 bg-slate-800 border border-slate-700 rounded-xl text-3xl font-bold text-white placeholder-slate-600 focus:outline-none focus:border-emerald-500"
                />
              </div>
              {errors.amountCents && (
                <p className="text-red-400 text-xs mt-1">{errors.amountCents.message}</p>
              )}
            </div>
          </div>

          {/* Description */}
          <div>
            <input
              {...register("description")}
              placeholder="e.g. Netflix, Gym Membership, Rent…"
              className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-xl text-white placeholder-slate-600 focus:outline-none focus:border-emerald-500"
            />
            {errors.description && (
              <p className="text-red-400 text-xs mt-1">{errors.description.message}</p>
            )}
          </div>

          {/* Frequency */}
          <div>
            <p className="text-xs text-slate-500 uppercase tracking-wider mb-2">Frequency</p>
            <div className="flex flex-wrap gap-2">
              {(["DAILY","WEEKLY","BIWEEKLY","MONTHLY","QUARTERLY","YEARLY"] as const).map((f) => (
                <button
                  key={f}
                  type="button"
                  onClick={() => { setSelectedFreq(f); setValue("frequency", f); }}
                  className={cn(
                    "px-3 py-1.5 rounded-lg text-xs font-medium transition-all",
                    selectedFreq === f
                      ? "bg-emerald-500/20 text-emerald-300 ring-1 ring-emerald-500/50"
                      : "bg-slate-800 text-slate-400"
                  )}
                >
                  {FREQ_LABEL[f]}
                </button>
              ))}
            </div>
          </div>

          {/* Dates */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider mb-1">Start Date</p>
              <input
                type="date"
                value={watchedStartDate ?? ""}
                onChange={(e) => setValue("startDate", e.target.value)}
                className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-white text-sm focus:outline-none focus:border-emerald-500"
              />
            </div>
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider mb-1">End Date (optional)</p>
              <input
                type="date"
                value={watchedEndDate ?? ""}
                onChange={(e) => setValue("endDate", e.target.value || undefined)}
                min={watchedStartDate}
                className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-white text-sm focus:outline-none focus:border-emerald-500"
              />
            </div>
          </div>

          {/* Category */}
          <div>
            <p className="text-xs text-slate-500 uppercase tracking-wider mb-2">Category</p>
            <div className="flex gap-2 overflow-x-auto pb-1 no-scrollbar">
              <button
                type="button"
                onClick={() => setValue("categoryId", undefined)}
                className={cn(
                  "shrink-0 px-3 py-1.5 rounded-lg text-xs font-medium transition-all",
                  !watchedCategory
                    ? "bg-emerald-500/20 text-emerald-300 ring-1 ring-emerald-500/50"
                    : "bg-slate-800 text-slate-400"
                )}
              >
                None
              </button>
              {visibleCats.map((cat) => (
                <button
                  key={cat.id}
                  type="button"
                  onClick={() => setValue("categoryId", cat.id)}
                  className={cn(
                    "shrink-0 px-3 py-1.5 rounded-lg text-xs font-medium transition-all whitespace-nowrap",
                    watchedCategory === cat.id
                      ? "bg-emerald-500/20 text-emerald-300 ring-1 ring-emerald-500/50"
                      : "bg-slate-800 text-slate-400"
                  )}
                >
                  <CategoryIcon icon={cat.icon} color={cat.color} className="h-3.5 w-3.5 shrink-0" />{cat.name}
                </button>
              ))}
            </div>
          </div>

          {/* Account */}
          <div>
            <p className="text-xs text-slate-500 uppercase tracking-wider mb-2">Pay From / Receive To</p>
            <div className="flex gap-2 overflow-x-auto pb-1 no-scrollbar">
              {accounts.filter((a) => !a.isArchived).map((acct) => (
                <button
                  key={acct.id}
                  type="button"
                  onClick={() => setValue("bankAccountId", acct.id)}
                  className={cn(
                    "shrink-0 flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all",
                    watchedAccount === acct.id
                      ? "bg-emerald-500/20 text-emerald-300 ring-1 ring-emerald-500/50"
                      : "bg-slate-800 text-slate-400"
                  )}
                >
                  <span>{accountIcon(acct.type)}</span>
                  <span>{acct.name}</span>
                </button>
              ))}
            </div>
            {errors.bankAccountId && (
              <p className="text-red-400 text-xs mt-1">{errors.bankAccountId.message}</p>
            )}
          </div>

          {/* Merchant & Color */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider mb-1">Merchant (optional)</p>
              <input
                {...register("merchantName")}
                placeholder="e.g. Netflix Inc."
                className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-white text-sm placeholder-slate-600 focus:outline-none focus:border-emerald-500"
              />
            </div>
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider mb-1">Color</p>
              <div className="flex gap-1.5 flex-wrap">
                {PRESET_COLORS.map((c) => (
                  <button
                    key={c}
                    type="button"
                    onClick={() => { setSelectedColor(c); setValue("color", c); }}
                    style={{ backgroundColor: c }}
                    className={cn(
                      "w-6 h-6 rounded-full transition-transform",
                      selectedColor === c ? "ring-2 ring-white scale-110" : ""
                    )}
                  />
                ))}
              </div>
            </div>
          </div>

          {/* Reminder */}
          <div>
            <p className="text-xs text-slate-500 uppercase tracking-wider mb-2">
              Reminder — {watchedReminderDays === 0 ? "None" : `${watchedReminderDays} day${watchedReminderDays > 1 ? "s" : ""} before`}
            </p>
            <input
              type="range"
              min={0}
              max={14}
              step={1}
              value={watchedReminderDays ?? 0}
              onChange={(e) => setValue("reminderDays", parseInt(e.target.value))}
              className="w-full accent-emerald-500"
            />
          </div>

          {mutationError && (
            <div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-xl text-red-300 text-sm">
              <AlertCircle className="h-4 w-4 shrink-0" />
              {mutationError.message}
            </div>
          )}

          <button
            type="submit"
            disabled={isSubmitting}
            className={cn(
              "w-full py-4 rounded-xl font-bold text-white text-base transition-all",
              selectedType === "EXPENSE"
                ? "bg-red-500 active:bg-red-600"
                : "bg-emerald-500 active:bg-emerald-600",
              isSubmitting && "opacity-60"
            )}
          >
            {isSubmitting
              ? "Saving…"
              : existing
              ? "Save Changes"
              : selectedType === "EXPENSE" ? "Add Recurring Expense" : "Add Recurring Income"}
          </button>
        </form>
      </SheetContent>
    </Sheet>
  );
}

// ── Recurring Card ────────────────────────────────────────────

interface RecurringCardProps {
  item: RecurringItem;
  onEdit: (item: RecurringItem) => void;
}

function RecurringCard({ item, onEdit }: RecurringCardProps) {
  const toggle = useToggleRecurring();
  const skip   = useSkipRecurring();
  const del    = useDeleteRecurring();
  const [confirmDelete, setConfirmDelete] = useState(false);

  const due = dueDaysLabel(item.nextDueDate);
  const monthly = monthlyEquiv(item);

  return (
    <div className={cn(
      "bg-slate-800/60 border rounded-2xl p-4 transition-all",
      item.isActive ? "border-slate-700/60" : "border-slate-700/30 opacity-60"
    )}>
      <div className="flex items-start gap-3">
        {/* Icon */}
        <div
          className="w-11 h-11 rounded-xl flex items-center justify-center text-xl shrink-0"
          style={{ backgroundColor: (item.color ?? "#10b981") + "22" }}
        >
          {item.icon ?? (item.type === "EXPENSE" ? "💸" : "💰")}
        </div>

        {/* Main info */}
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2">
            <div className="min-w-0">
              <p className="font-semibold text-white text-sm truncate">{item.description}</p>
              {item.merchantName && (
                <p className="text-xs text-slate-500 truncate">{item.merchantName}</p>
              )}
            </div>
            <div className="text-right shrink-0">
              <p className={cn("font-bold text-base", item.type === "EXPENSE" ? "text-red-400" : "text-emerald-400")}>
                {item.type === "EXPENSE" ? "-" : "+"}{formatCents(item.amountCents)}
              </p>
              {item.frequency !== "MONTHLY" && (
                <p className="text-xs text-slate-500">≈ {formatCents(monthly)}/mo</p>
              )}
            </div>
          </div>

          {/* Chips row */}
          <div className="flex items-center gap-1.5 mt-2 flex-wrap">
            <span className={cn("text-xs px-2 py-0.5 rounded-full font-medium", FREQ_COLOR[item.frequency])}>
              {FREQ_LABEL[item.frequency]}
            </span>
            {item.category && (
              <span className="text-xs px-2 py-0.5 rounded-full bg-slate-700 text-slate-300">
                <CategoryIcon icon={item.category.icon} color={item.category.color} className="h-3 w-3 shrink-0" />{item.category.name}
              </span>
            )}
            <span className="text-xs px-2 py-0.5 rounded-full bg-slate-700 text-slate-400">
              {accountIcon(item.bankAccount.type)} {item.bankAccount.name}
            </span>
          </div>

          {/* Next due */}
          <div className="flex items-center gap-1.5 mt-2">
            <CalendarClock className="h-3.5 w-3.5 text-slate-500" />
            <span className="text-xs text-slate-500">Next:</span>
            <span className={cn("text-xs font-medium", due.color)}>{due.label}</span>
            <span className="text-xs text-slate-600">
              · {new Date(item.nextDueDate).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
            </span>
          </div>
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center justify-between mt-3 pt-3 border-t border-slate-700/40">
        <div className="flex items-center gap-1">
          {/* Pause / Resume */}
          <button
            onClick={() => toggle.mutate({ id: item.id, isActive: !item.isActive })}
            disabled={toggle.isPending}
            className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-slate-700/60 hover:bg-slate-700 text-slate-300 text-xs font-medium transition-colors"
          >
            {item.isActive
              ? <><Pause className="h-3.5 w-3.5" /> Pause</>
              : <><Play className="h-3.5 w-3.5 text-emerald-400" /> Resume</>
            }
          </button>

          {/* Skip next */}
          {item.isActive && (
            <button
              onClick={() => skip.mutate(item.id)}
              disabled={skip.isPending}
              className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-slate-700/60 hover:bg-slate-700 text-slate-400 text-xs font-medium transition-colors"
              title="Skip next occurrence"
            >
              <SkipForward className="h-3.5 w-3.5" /> Skip
            </button>
          )}
        </div>

        <div className="flex items-center gap-1">
          <button
            onClick={() => onEdit(item)}
            className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition-colors"
          >
            <Pencil className="h-3.5 w-3.5" />
          </button>
          {confirmDelete ? (
            <div className="flex items-center gap-1">
              <button
                onClick={() => del.mutate(item.id)}
                className="px-2 py-1 text-xs rounded-lg bg-red-500/20 text-red-300 hover:bg-red-500/30"
              >
                Confirm
              </button>
              <button
                onClick={() => setConfirmDelete(false)}
                className="px-2 py-1 text-xs rounded-lg bg-slate-700 text-slate-400"
              >
                Cancel
              </button>
            </div>
          ) : (
            <button
              onClick={() => setConfirmDelete(true)}
              className="p-1.5 rounded-lg text-slate-400 hover:text-red-400 hover:bg-red-500/10 transition-colors"
            >
              <Trash2 className="h-3.5 w-3.5" />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────

type FilterTab = "ALL" | "EXPENSE" | "INCOME" | "PAUSED";

export default function RecurringPage() {
  const { data: items = [], isLoading } = useRecurring();
  const [formOpen, setFormOpen] = useState(false);
  const [editItem, setEditItem] = useState<RecurringItem | null>(null);
  const [filter, setFilter] = useState<FilterTab>("ALL");

  // Summary stats
  const activeItems = items.filter((i) => i.isActive);
  const pausedItems = items.filter((i) => !i.isActive);
  const totalMonthlyExpense = activeItems
    .filter((i) => i.type === "EXPENSE")
    .reduce((sum, i) => sum + monthlyEquiv(i), 0);
  const totalMonthlyIncome = activeItems
    .filter((i) => i.type === "INCOME")
    .reduce((sum, i) => sum + monthlyEquiv(i), 0);

  // Upcoming in 7 days
  const in7 = new Date(); in7.setDate(in7.getDate() + 7);
  const upcomingItems = activeItems
    .filter((i) => new Date(i.nextDueDate) <= in7)
    .sort((a, b) => a.nextDueDate.localeCompare(b.nextDueDate));

  // Filtered list
  const filtered = items.filter((i) => {
    if (filter === "EXPENSE") return i.type === "EXPENSE" && i.isActive;
    if (filter === "INCOME")  return i.type === "INCOME"  && i.isActive;
    if (filter === "PAUSED")  return !i.isActive;
    return true;
  });

  function handleEdit(item: RecurringItem) {
    setEditItem(item);
    setFormOpen(true);
  }

  function handleAdd() {
    setEditItem(null);
    setFormOpen(true);
  }

  return (
    <div className="max-w-2xl mx-auto space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Recurring</h1>
          <p className="text-sm text-slate-400">Subscriptions &amp; scheduled payments</p>
        </div>
        <Button
          onClick={handleAdd}
          className="bg-emerald-500 hover:bg-emerald-600 text-white gap-1.5 rounded-xl"
          size="sm"
        >
          <Plus className="h-4 w-4" /> Add
        </Button>
      </div>

      {/* Summary cards */}
      <div className="grid grid-cols-2 gap-3">
        <div className="bg-red-500/10 border border-red-500/20 rounded-2xl p-4">
          <div className="flex items-center gap-2 mb-1">
            <TrendingDown className="h-4 w-4 text-red-400" />
            <span className="text-xs text-red-400 font-medium">Monthly Out</span>
          </div>
          <p className="text-2xl font-bold text-white">{formatCents(totalMonthlyExpense)}</p>
          <p className="text-xs text-red-400/70 mt-0.5">{activeItems.filter(i => i.type === "EXPENSE").length} active</p>
        </div>
        <div className="bg-emerald-500/10 border border-emerald-500/20 rounded-2xl p-4">
          <div className="flex items-center gap-2 mb-1">
            <TrendingUp className="h-4 w-4 text-emerald-400" />
            <span className="text-xs text-emerald-400 font-medium">Monthly In</span>
          </div>
          <p className="text-2xl font-bold text-white">{formatCents(totalMonthlyIncome)}</p>
          <p className="text-xs text-emerald-400/70 mt-0.5">{activeItems.filter(i => i.type === "INCOME").length} active</p>
        </div>
      </div>

      {/* Upcoming strip */}
      {upcomingItems.length > 0 && (
        <div>
          <p className="text-xs text-slate-500 uppercase tracking-wider mb-2 flex items-center gap-1.5">
            <CalendarClock className="h-3.5 w-3.5" /> Due in the next 7 days
          </p>
          <div className="flex gap-3 overflow-x-auto pb-1 no-scrollbar">
            {upcomingItems.map((item) => {
              const due = dueDaysLabel(item.nextDueDate);
              return (
                <div
                  key={item.id}
                  className="shrink-0 bg-slate-800 border border-slate-700/60 rounded-2xl p-3 w-36"
                >
                  <div className="text-xl mb-1">{item.icon ?? "📅"}</div>
                  <p className="text-xs font-medium text-white truncate">{item.description}</p>
                  <p className={cn("text-xs font-semibold mt-1", due.color)}>{due.label}</p>
                  <p className={cn("text-sm font-bold mt-0.5", item.type === "EXPENSE" ? "text-red-400" : "text-emerald-400")}>
                    {item.type === "EXPENSE" ? "-" : "+"}{formatCents(item.amountCents)}
                  </p>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Filter tabs */}
      <div className="flex gap-1 bg-slate-800/60 p-1 rounded-xl">
        {([
          ["ALL",    "All"],
          ["EXPENSE","Expenses"],
          ["INCOME", "Income"],
          ["PAUSED", `Paused${pausedItems.length > 0 ? ` (${pausedItems.length})` : ""}`],
        ] as [FilterTab, string][]).map(([val, label]) => (
          <button
            key={val}
            onClick={() => setFilter(val)}
            className={cn(
              "flex-1 py-1.5 rounded-lg text-xs font-medium transition-all",
              filter === val
                ? "bg-slate-700 text-white"
                : "text-slate-500 hover:text-slate-300"
            )}
          >
            {label}
          </button>
        ))}
      </div>

      {/* List */}
      {isLoading ? (
        <div className="text-center py-12 text-slate-500">Loading…</div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-16 space-y-3">
          <div className="w-16 h-16 rounded-2xl bg-slate-800 flex items-center justify-center mx-auto text-3xl">
            <RefreshCw className="h-7 w-7 text-slate-600" />
          </div>
          <p className="text-slate-400 font-medium">No recurring transactions</p>
          <p className="text-slate-600 text-sm">
            {filter === "ALL"
              ? "Add subscriptions and scheduled bills here."
              : `No ${filter.toLowerCase()} recurring transactions.`}
          </p>
          {filter === "ALL" && (
            <Button
              onClick={handleAdd}
              variant="outline"
              className="border-slate-700 text-slate-300 hover:bg-slate-800"
            >
              <Plus className="h-4 w-4 mr-1.5" /> Add your first recurring
            </Button>
          )}
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map((item) => (
            <RecurringCard key={item.id} item={item} onEdit={handleEdit} />
          ))}
        </div>
      )}

      {/* Add/Edit form sheet */}
      <RecurringForm
        open={formOpen}
        onClose={() => { setFormOpen(false); setEditItem(null); }}
        existing={editItem}
      />
    </div>
  );
}
