"use client";

import { useEffect, useRef, useState } from "react";
import { useForm, Controller, type SubmitHandler, type Resolver } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { transactionSchema, type TransactionInput } from "@/lib/validations/transaction";
import {
  useCreateTransaction,
  useUpdateTransaction,
  type TransactionWithRelations,
} from "@/hooks/use-transactions";
import { useBankAccounts, useCreateBankAccount } from "@/hooks/use-bank-accounts";
import { useCategories, type CategoryWithPref } from "@/hooks/use-categories";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { useCurrency } from "@/hooks/use-currency";
import {
  CalendarDays, Check, ChevronDown, ChevronUp, RefreshCw, Sparkles,
  MoreHorizontal,
} from "lucide-react";
import { ICON_MAP } from "@/components/ui/category-icon";

const CURRENCY_SYMBOL: Record<string, string> = {
  USD: "$", EUR: "€", GBP: "£", LKR: "Rs", INR: "₹",
  JPY: "¥", AUD: "A$", CAD: "C$", SGD: "S$", AED: "د.إ",
};

// ── Constants ──────────────────────────────────────────────────────────────

const FREQ_OPTIONS = [
  { value: "DAILY",     label: "Daily" },
  { value: "WEEKLY",    label: "Weekly" },
  { value: "BIWEEKLY",  label: "Every 2 weeks" },
  { value: "MONTHLY",   label: "Monthly" },
  { value: "QUARTERLY", label: "Quarterly" },
  { value: "YEARLY",    label: "Yearly" },
];

const TYPE_ORDER = ["EXPENSE", "INCOME", "TRANSFER"] as const;

const TYPE_CFG = {
  EXPENSE:  { label: "Expense",  color: "#f43f5e", submit: "bg-rose-600 hover:bg-rose-500 shadow-rose-600/25"      },
  INCOME:   { label: "Income",   color: "#10b981", submit: "bg-emerald-600 hover:bg-emerald-500 shadow-emerald-600/25" },
  TRANSFER: { label: "Transfer", color: "#3b82f6", submit: "bg-blue-600 hover:bg-blue-500 shadow-blue-600/25"       },
} as const;

// Keyword → category-name-fragment map for auto-detection
const KEYWORD_HINTS: [RegExp, string][] = [
  // Food & Beverages
  [/coffee|starbucks|cafe|espresso|latte|cappuccino|bubble tea|juice bar/i, "food & bev"],
  [/restaurant|food|lunch|dinner|breakfast|meal|eat|dining|pizza|burger|kfc|sushi|grill|bakery|takeout|takeaway|fast food/i, "food & bev"],
  // Groceries
  [/grocery|groceries|supermarket|vegetables|veggies|fruit|fresh market|keells|cargills|arpico/i, "grocer"],
  // Transportation
  [/uber|lyft|taxi|bus|train|subway|metro|pickme|grab|tuk|three.?wheel|commute|parking|toll/i, "transportation"],
  // Fuel
  [/fuel|petrol|filling station|ceypetco|laugfs|shell|gas station/i, "fuel"],
  // Electricity
  [/electricity|electric bill|ceb|leco|power bill|electric charge/i, "electric"],
  // Water & Gas
  [/water bill|water supply|nwsdb|lpg|cooking gas|gas cylinder|water meter/i, "water"],
  // Telecommunication
  [/internet|wifi|broadband|fiber|isp|slt|dialog|mobitel|airtel|hutch|phone bill|mobile bill|data plan|recharge|mobile top.?up/i, "telecom"],
  // Entertainment
  [/netflix|spotify|movie|cinema|game|steam|playstation|xbox|prime video|disney|hulu|youtube premium/i, "entertain"],
  // Subscriptions
  [/subscription|adobe|microsoft 365|apple music|icloud|dropbox|antivirus/i, "subscr"],
  // Shopping
  [/amazon|shop|store|mall|cloth|fashion|outfit|online order|daraz/i, "shopping"],
  // Healthcare
  [/doctor|hospital|medicine|pharmacy|health|gym|fitness|dental|medical|clinic|channeling|lab test/i, "health"],
  // Education
  [/school|college|university|course|tuition|class|study|workshop|training/i, "educ"],
  // Income triggers (for income transactions)
  [/salary|paycheck|payroll|bonus|commission|freelance|wage/i,  "salary"],
  // House Rent
  [/rent|lease|landlord|mortgage|house payment/i, "house rent"],
  // Insurance
  [/insurance|premium|policy|life insurance|health insurance/i, "insur"],
];

// ── CategoryTile ───────────────────────────────────────────────────────────

interface TileProps {
  cat: CategoryWithPref;
  isActive: boolean;
  isAiPick: boolean;
  onSelect: () => void;
}

function CategoryTile({ cat, isActive, isAiPick, onSelect }: TileProps) {
  const Icon  = ICON_MAP[cat.icon ?? ""] ?? MoreHorizontal;
  const color = isAiPick ? "#a78bfa" : (cat.color ?? "#64748b");

  const isPaid    = cat.paidThisPeriod === true;
  const isOverdue = cat.paidThisPeriod === false && cat.billingCycle !== "NONE";

  // Format next due date: "Jul 24"
  const nextLabel = (() => {
    if (!isPaid || !cat.nextDueDate) return null;
    const d = new Date(cat.nextDueDate);
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  })();

  return (
    <button
      type="button"
      onClick={onSelect}
      className={cn(
        "relative flex flex-col items-center gap-2 py-3 px-1.5 rounded-2xl border transition-all duration-150 active:scale-95",
        isActive
          ? "shadow-sm"
          : isPaid
          ? "bg-slate-800/40 border-slate-700/30 opacity-50 hover:opacity-70"
          : "bg-slate-800/70 border-slate-700/50 hover:bg-slate-800 hover:border-slate-600"
      )}
      style={isActive ? {
        background:  `linear-gradient(135deg, ${color}18 0%, ${color}0d 100%)`,
        borderColor: `${color}70`,
        boxShadow:   `0 0 0 1px ${color}40 inset`,
      } : undefined}
    >
      {/* Status dot */}
      {isAiPick && (
        <span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-violet-400 shadow-[0_0_4px_#a78bfa]" />
      )}
      {!isAiPick && isPaid && !isActive && (
        <span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-emerald-500" title="Paid this month" />
      )}
      {!isAiPick && isOverdue && !isActive && (
        <span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-amber-400 shadow-[0_0_4px_#fbbf24]" title="Not paid yet" />
      )}

      {/* Icon */}
      <div
        className="w-10 h-10 rounded-xl flex items-center justify-center transition-all duration-150"
        style={{
          backgroundColor: isActive ? `${color}28` : `${color}14`,
          boxShadow:       isActive ? `0 2px 8px ${color}30` : "none",
        }}
      >
        <Icon
          className="h-[18px] w-[18px] transition-colors duration-150"
          style={{ color: isActive ? color : isPaid ? "#475569" : "#64748b" }}
        />
      </div>

      {/* Name */}
      <span
        className="text-[9.5px] font-medium text-center leading-tight line-clamp-2 w-full break-words transition-colors duration-150"
        style={{ color: isActive ? color : isPaid ? "#475569" : "#94a3b8" }}
      >
        {cat.name}
      </span>

      {/* Paid → next due date; overdue → amber dot already shown */}
      {isPaid && !isActive && nextLabel && (
        <span className="text-[8px] text-emerald-700 font-semibold -mt-1 leading-none">
          Next {nextLabel}
        </span>
      )}
    </button>
  );
}

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

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

// ── Date helpers ───────────────────────────────────────────────────────────

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

function toDateStr(v: string | Date | undefined): string {
  if (!v) return todayStr();
  const d = v instanceof Date ? v : new Date(v);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

function getRecentDates(n = 5) {
  return Array.from({ length: n }, (_, i) => {
    const d = new Date();
    d.setDate(d.getDate() - i);
    return d;
  });
}

function quickDateLabel(d: Date, i: number): string {
  if (i === 0) return "Today";
  if (i === 1) return "Yesterday";
  return d.toLocaleDateString("en-US", { weekday: "short" });
}

// ── Component ──────────────────────────────────────────────────────────────

interface Props {
  open: boolean;
  onClose: () => void;
  existing?: TransactionWithRelations;
  defaultType?: "EXPENSE" | "INCOME" | "TRANSFER";
  defaultFromAccountId?: string;
}

export function TransactionDialog({ open, onClose, existing, defaultType, defaultFromAccountId }: Props) {
  const create     = useCreateTransaction();
  const update     = useUpdateTransaction();
  const createAcct = useCreateBankAccount();
  const { data: accounts   = [] } = useBankAccounts();
  const { data: categories = [] } = useCategories();

  const isEdit     = !!existing;
  const userCurrency = useCurrency();
  const currencySymbol = CURRENCY_SYMBOL[userCurrency] ?? userCurrency;

  const [showMore,        setShowMore]        = useState(false);
  const [isCreatingCash,  setCreatingCash]    = useState(false);
  const [amountStr,       setAmountStr]       = useState("");
  const [aiSuggested,     setAiSuggested]     = useState<string | undefined>();
  const [saved,           setSaved]           = useState(false);

  const amountRef       = useRef<HTMLInputElement>(null);
  const dateInputRef    = useRef<HTMLInputElement>(null);
  const formInitialized = useRef(false);

  const {
    register,
    handleSubmit,
    control,
    watch,
    setValue,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<TransactionInput>({
    resolver: zodResolver(transactionSchema) as Resolver<TransactionInput>,
    defaultValues: {
      type:        "EXPENSE",
      date:        new Date(`${todayStr()}T12:00:00`).toISOString(),
      currency:    userCurrency,
      isRecurring: false,
      tags:        [],
    },
  });

  const txType        = watch("type");
  const isRecurring   = watch("isRecurring");
  const watchedCat    = watch("categoryId");
  const watchedDate   = watch("date");
  const watchedAcctId = watch("bankAccountId");

  const typeIndex = TYPE_ORDER.indexOf(txType);
  const cfg       = TYPE_CFG[txType];

  const cashAccount    = accounts.find((a) => a.type === "CASH" || a.type === "WALLET");
  const hasCashAccount = !!cashAccount;

  // Auto-focus amount on open
  useEffect(() => {
    if (open && !isEdit) {
      const t = setTimeout(() => amountRef.current?.focus(), 350);
      return () => clearTimeout(t);
    }
  }, [open, isEdit]);

  // Reset form once per open session
  useEffect(() => {
    if (!open) {
      formInitialized.current = false;
      setSaved(false);
      return;
    }
    if (formInitialized.current) return;
    formInitialized.current = true;

    if (existing) {
      setShowMore(true);
      setAmountStr((existing.amountCents / 100).toFixed(2));
      setAiSuggested(undefined);
      reset({
        bankAccountId:  existing.bankAccount.id,
        categoryId:     existing.category?.id,
        type:           existing.type,
        amountCents:    existing.amountCents,
        description:    existing.description,
        notes:          existing.notes ?? undefined,
        date:           existing.date,
        currency:       "USD",
        isRecurring:    existing.isRecurring ?? false,
        recurrenceFreq: (existing.recurrenceFreq as TransactionInput["recurrenceFreq"]) ?? undefined,
        recurrenceEnd:  existing.recurrenceEnd ?? undefined,
        tags:           (existing.tags as string[]) ?? [],
      });
    } else {
      setShowMore(false);
      setAmountStr("");
      setAiSuggested(undefined);
      reset({
        type:          defaultType ?? "EXPENSE",
        date:          new Date(`${todayStr()}T12:00:00`).toISOString(),
        currency:      userCurrency,
        isRecurring:   false,
        tags:          [],
        bankAccountId: defaultFromAccountId ?? accounts[0]?.id,
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, existing]);

  // Fallback: pick first account if none selected yet
  useEffect(() => {
    if (!open || !accounts.length || watchedAcctId || isEdit) return;
    setValue("bankAccountId", accounts[0].id);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [accounts]);

  // Auto-detect category from description text
  function detectCategory(desc: string) {
    if (!desc || desc.length < 3) {
      setAiSuggested(undefined);
      return;
    }
    const filtered = categories.filter((c) => c.type === txType);
    for (const [pattern, hint] of KEYWORD_HINTS) {
      if (pattern.test(desc)) {
        const match = filtered.find((c) => c.name.toLowerCase().includes(hint));
        if (match) {
          setAiSuggested(match.id);
          setValue("categoryId", match.id);
          return;
        }
      }
    }
    setAiSuggested(undefined);
  }

  // Cash wallet auto-create
  async function handleCashTap() {
    if (cashAccount) { setValue("bankAccountId", cashAccount.id); return; }
    setCreatingCash(true);
    try {
      const a = await createAcct.mutateAsync({
        name: "Cash Wallet", type: "CASH",
        balanceCents: 0, currency: "USD",
        includeInNetWorth: true, color: "#10b981",
      });
      setValue("bankAccountId", a.id);
    } finally { setCreatingCash(false); }
  }

  // Bump amount by n
  function addAmount(n: number) {
    const next = Math.max(0, parseFloat(amountStr || "0") + n);
    const str  = next % 1 === 0 ? String(next) : next.toFixed(2);
    setAmountStr(str);
    setValue("amountCents", Math.round(next * 100));
  }

  // Update amount from raw string, sanitise to 2 dp
  function handleAmountChange(raw: string) {
    const clean = raw.replace(/[^0-9.]/g, "");
    const parts = clean.split(".");
    const final = parts.length > 1
      ? `${parts[0]}.${parts.slice(1).join("").slice(0, 2)}`
      : clean;
    setAmountStr(final);
    setValue("amountCents", Math.round(parseFloat(final || "0") * 100));
  }

  const onSubmit: SubmitHandler<TransactionInput> = async (data) => {
    if (isEdit) {
      await update.mutateAsync({ id: existing!.id, data });
    } else {
      await create.mutateAsync(data);
    }
    setSaved(true);
    setTimeout(onClose, 700);
  };

  const allForType = txType === "TRANSFER"
    ? []
    : categories.filter((c) => c.type === txType && c.isEnabled !== false);

  const regularCats = allForType.filter((c) => !c.billingCycle || c.billingCycle === "NONE");

  // Periodic: unpaid first (amber indicator), paid last (dimmed with "Next" date)
  const periodicRaw = allForType.filter((c) => c.billingCycle && c.billingCycle !== "NONE");
  const periodicCats = [
    ...periodicRaw.filter((c) => c.paidThisPeriod !== true),
    ...periodicRaw.filter((c) => c.paidThisPeriod === true),
  ];


  const currentDateStr = toDateStr(watchedDate);
  const recentDates    = getRecentDates(5);
  const isCustomDate   = !recentDates.some((d) => toDateStr(d) === currentDateStr);

  const descriptionPlaceholder =
    txType === "INCOME"   ? "Where did this come from?" :
    txType === "TRANSFER" ? "What's this transfer for?" :
                            "What's this for?";

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

        {/* Drag handle */}
        <div className="flex justify-center pt-3">
          <div className="w-10 h-1 rounded-full bg-slate-700" />
        </div>

        <form onSubmit={handleSubmit(onSubmit)} noValidate>

          {/* ── Type toggle — animated pill ──────────────── */}
          <div className="px-4 pt-4 pb-2">
            <div className="relative flex bg-slate-800 rounded-2xl p-1">
              {/* Sliding indicator */}
              <div
                className="absolute top-1 bottom-1 rounded-xl transition-all duration-300 ease-out pointer-events-none"
                style={{
                  width:      "calc(33.333% - 1.33px)",
                  left:       `calc(${typeIndex * 33.333}% + 4px)`,
                  background: cfg.color,
                  boxShadow:  `0 4px 16px ${cfg.color}50`,
                }}
              />
              {TYPE_ORDER.map((t) => (
                <button
                  key={t}
                  type="button"
                  onClick={() => {
                    setValue("type", t);
                    setValue("categoryId", undefined);
                    setAiSuggested(undefined);
                  }}
                  className={cn(
                    "relative flex-1 py-2.5 rounded-xl text-sm font-semibold z-10",
                    "transition-colors duration-200",
                    txType === t ? "text-white" : "text-slate-500 hover:text-slate-300"
                  )}
                >
                  {TYPE_CFG[t].label}
                </button>
              ))}
            </div>
          </div>

          {/* ── Amount hero ──────────────────────────────── */}
          <div className="flex flex-col items-center py-5 px-4">
            <div className="flex items-baseline gap-1.5">
              <span
                className="text-3xl font-light transition-colors duration-300"
                style={{ color: cfg.color }}
              >
                {currencySymbol}
              </span>
              <input
                ref={amountRef}
                type="text"
                inputMode="decimal"
                placeholder="0"
                value={amountStr}
                onChange={(e) => handleAmountChange(e.target.value)}
                className="text-6xl font-bold bg-transparent border-none outline-none text-white text-center w-52 placeholder:text-slate-700"
              />
            </div>

            {/* Quick-add chips */}
            <div className="flex gap-2 mt-3 flex-wrap justify-center">
              {[5, 10, 20, 50, 100].map((n) => (
                <button
                  key={n}
                  type="button"
                  onClick={() => addAmount(n)}
                  className="px-3 py-1.5 rounded-full text-xs font-semibold border bg-slate-800/80 border-slate-700 text-slate-400 hover:border-slate-500 hover:text-slate-200 active:scale-95 transition-all"
                >
                  +${n}
                </button>
              ))}
            </div>

            {errors.amountCents && (
              <p className="text-xs text-rose-400 mt-2">{errors.amountCents.message}</p>
            )}
          </div>

          <div className="px-4 space-y-4">

            {/* ── Description ─────────────────────────────── */}
            <div className="space-y-1">
              <Input
                {...register("description", {
                  onChange: (e) => detectCategory(e.target.value),
                })}
                placeholder={descriptionPlaceholder}
                autoComplete="off"
                className="bg-slate-800/80 border-slate-700 text-white placeholder:text-slate-500 rounded-xl h-12 text-sm"
              />
              {errors.description && (
                <p className="text-xs text-rose-400">{errors.description.message}</p>
              )}
            </div>

            {/* ── Category grid ────────────────────────────── */}
            {allForType.length > 0 && (
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <p className="text-[10px] text-slate-500 uppercase tracking-widest font-semibold">Category</p>
                  {aiSuggested && watchedCat === aiSuggested && (
                    <span className="flex items-center gap-1 text-[10px] text-violet-400 font-semibold">
                      <Sparkles className="h-3 w-3" />
                      Auto-detected
                    </span>
                  )}
                </div>

                {/* Regular expenses — always first */}
                {regularCats.length > 0 && (
                  <div className="space-y-2">
                    {periodicCats.length > 0 && txType === "EXPENSE" && (
                      <p className="text-[9px] text-slate-600 uppercase tracking-widest font-medium">
                        Expenses
                      </p>
                    )}
                    <div className="grid grid-cols-4 gap-2">
                      {regularCats.map((cat) => (
                        <CategoryTile
                          key={cat.id}
                          cat={cat}
                          isActive={watchedCat === cat.id}
                          isAiPick={watchedCat === cat.id && cat.id === aiSuggested}
                          onSelect={() => {
                            setValue("categoryId", watchedCat === cat.id ? undefined : cat.id);
                            setAiSuggested(undefined);
                          }}
                        />
                      ))}
                    </div>
                  </div>
                )}

                {/* Monthly / Periodic Bills — always second */}
                {periodicCats.length > 0 && txType === "EXPENSE" && (
                  <div className="space-y-2">
                    <p className="text-[9px] text-slate-600 uppercase tracking-widest font-medium">
                      Monthly Bills
                    </p>
                    <div className="grid grid-cols-4 gap-2">
                      {periodicCats.map((cat) => (
                        <CategoryTile
                          key={cat.id}
                          cat={cat}
                          isActive={watchedCat === cat.id}
                          isAiPick={watchedCat === cat.id && cat.id === aiSuggested}
                          onSelect={() => {
                            setValue("categoryId", watchedCat === cat.id ? undefined : cat.id);
                            setAiSuggested(undefined);
                          }}
                        />
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* ── Account chips ────────────────────────────── */}
            <div className="space-y-2">
              <p className={cn(
                "text-[10px] uppercase tracking-wider",
                errors.bankAccountId ? "text-rose-400" : "text-slate-600"
              )}>
                {txType === "TRANSFER" ? "From account" : "Pay from"}
                {errors.bankAccountId && ` — ${errors.bankAccountId.message}`}
              </p>
              <div className="flex gap-2 overflow-x-auto pb-1 -mx-4 px-4 scrollbar-none">
                {!hasCashAccount && (
                  <button
                    type="button"
                    onClick={handleCashTap}
                    disabled={isCreatingCash}
                    className="flex items-center gap-1.5 px-3 py-2 rounded-full text-xs font-medium whitespace-nowrap shrink-0 border transition-all active:scale-95 bg-amber-500/10 text-amber-300 border-amber-500/30 hover:bg-amber-500/20 disabled:opacity-50"
                  >
                    💵 {isCreatingCash ? "Creating…" : "Cash"}
                  </button>
                )}
                {accounts.map((acc) => (
                  <button
                    key={acc.id}
                    type="button"
                    onClick={() => setValue("bankAccountId", acc.id)}
                    className={cn(
                      "flex items-center gap-1.5 px-3 py-2 rounded-full text-xs font-medium whitespace-nowrap shrink-0 border transition-all active:scale-95",
                      watchedAcctId === acc.id
                        ? "bg-emerald-500/20 text-emerald-300 border-emerald-500/40"
                        : "bg-slate-800 text-slate-400 border-slate-700 hover:text-slate-200 hover:border-slate-600"
                    )}
                  >
                    {accountIcon(acc.type)} {acc.name}
                  </button>
                ))}
              </div>
            </div>

            {/* ── Transfer destination ─────────────────────── */}
            {txType === "TRANSFER" && (
              <div className="space-y-2">
                <p className="text-[10px] text-slate-600 uppercase tracking-wider">To account</p>
                <Controller
                  name="transferToAccountId"
                  control={control}
                  render={({ field }) => (
                    <Select value={field.value ?? ""} onValueChange={field.onChange}>
                      <SelectTrigger className="bg-slate-800/80 border-slate-700 text-slate-300 rounded-xl h-11 text-sm">
                        <SelectValue placeholder="Choose destination…" />
                      </SelectTrigger>
                      <SelectContent className="bg-slate-800 border-slate-700">
                        {accounts
                          .filter((a) => a.id !== watchedAcctId)
                          .map((a) => (
                            <SelectItem key={a.id} value={a.id} className="text-slate-200 focus:bg-slate-700">
                              {accountIcon(a.type)} {a.name}
                            </SelectItem>
                          ))}
                      </SelectContent>
                    </Select>
                  )}
                />
              </div>
            )}

            {/* ── Quick date chips ─────────────────────────── */}
            <div className="space-y-2">
              <p className="text-[10px] text-slate-600 uppercase tracking-wider">Date</p>
              <div className="flex gap-2 overflow-x-auto pb-1 -mx-4 px-4 scrollbar-none">
                {recentDates.map((d, i) => {
                  const ds         = toDateStr(d);
                  const isSelected = currentDateStr === ds;
                  return (
                    <button
                      key={ds}
                      type="button"
                      onClick={() => setValue("date", new Date(`${ds}T12:00:00`).toISOString())}
                      className={cn(
                        "px-3 py-2 rounded-full text-xs font-medium whitespace-nowrap shrink-0 border transition-all active:scale-95",
                        isSelected
                          ? "bg-emerald-500/20 text-emerald-300 border-emerald-500/40"
                          : "bg-slate-800 text-slate-400 border-slate-700 hover:text-slate-200 hover:border-slate-600"
                      )}
                    >
                      {quickDateLabel(d, i)}
                    </button>
                  );
                })}

                {/* Calendar picker button — input lives outside the scroll container below */}
                <button
                  type="button"
                  onClick={() => {
                    const inp = dateInputRef.current as (HTMLInputElement & { showPicker?(): void }) | null;
                    if (!inp) return;
                    try { if (inp.showPicker) inp.showPicker(); else inp.click(); }
                    catch { inp.click(); }
                  }}
                  className={cn(
                    "inline-flex items-center gap-1.5 bg-slate-800 border rounded-full px-3 h-8 text-xs font-medium whitespace-nowrap shrink-0 transition-all active:scale-95",
                    isCustomDate
                      ? "text-emerald-300 border-emerald-500/40 bg-emerald-500/20"
                      : "text-slate-400 border-slate-700 hover:border-slate-600 hover:text-slate-200"
                  )}
                >
                  <CalendarDays className="h-3 w-3" />
                  {isCustomDate
                    ? new Date(`${currentDateStr}T12:00:00`).toLocaleDateString("en-US", { month: "short", day: "numeric" })
                    : "Pick"}
                </button>
              </div>
              {/* Input is outside the overflow-x container so it isn't clipped on mobile */}
              <input
                ref={dateInputRef}
                type="date"
                value={currentDateStr}
                onChange={(e) =>
                  setValue("date",
                    e.target.value
                      ? new Date(`${e.target.value}T12:00:00`).toISOString()
                      : new Date().toISOString()
                  )
                }
                className="sr-only"
                tabIndex={-1}
              />
            </div>

            {/* ── Notes & Repeat toggle ────────────────────── */}
            <button
              type="button"
              onClick={() => setShowMore(!showMore)}
              className="flex items-center gap-1.5 text-xs text-slate-600 hover:text-slate-400 transition-colors py-0.5 w-full"
            >
              {showMore ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
              {showMore ? "Hide options" : "Notes & repeat"}
            </button>

            {/* ── Expanded section ─────────────────────────── */}
            {showMore && (
              <div className="space-y-3">
                <Input
                  {...register("notes")}
                  placeholder="Notes (optional)"
                  className="bg-slate-800/80 border-slate-700 text-white placeholder:text-slate-500 rounded-xl h-11 text-sm"
                />

                <div className="rounded-xl border border-slate-700/50 bg-slate-800/30 p-3 space-y-3">
                  <label className="flex items-center gap-3 cursor-pointer select-none">
                    <Controller
                      name="isRecurring"
                      control={control}
                      render={({ field }) => (
                        <button
                          type="button"
                          role="switch"
                          aria-checked={field.value}
                          onClick={() => {
                            field.onChange(!field.value);
                            if (field.value) {
                              setValue("recurrenceFreq", undefined);
                              setValue("recurrenceEnd",  undefined);
                            }
                          }}
                          className={cn(
                            "relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border-2 border-transparent transition-colors",
                            field.value ? "bg-emerald-600" : "bg-slate-600"
                          )}
                        >
                          <span className={cn(
                            "pointer-events-none block h-4 w-4 rounded-full bg-white shadow-lg transition-transform",
                            field.value ? "translate-x-4" : "translate-x-0"
                          )} />
                        </button>
                      )}
                    />
                    <span className="flex items-center gap-1.5 text-sm font-medium text-slate-300">
                      <RefreshCw className="h-3.5 w-3.5 text-slate-400" />
                      Repeat this transaction
                    </span>
                  </label>

                  {isRecurring && (
                    <div className="grid grid-cols-2 gap-2 pt-1">
                      <Controller
                        name="recurrenceFreq"
                        control={control}
                        render={({ field }) => (
                          <Select value={field.value ?? ""} onValueChange={field.onChange}>
                            <SelectTrigger className="bg-slate-800 border-slate-600 text-slate-200 h-9 text-xs rounded-xl">
                              <SelectValue placeholder="Frequency" />
                            </SelectTrigger>
                            <SelectContent className="bg-slate-800 border-slate-600">
                              {FREQ_OPTIONS.map((o) => (
                                <SelectItem key={o.value} value={o.value} className="text-slate-200 focus:bg-slate-700 text-xs">
                                  {o.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        )}
                      />
                      <input
                        type="date"
                        onChange={(e) =>
                          setValue("recurrenceEnd",
                            e.target.value
                              ? new Date(`${e.target.value}T12:00:00`).toISOString()
                              : undefined
                          )
                        }
                        className="bg-slate-800 border border-slate-600 text-white h-9 text-xs rounded-xl px-2"
                      />
                    </div>
                  )}
                </div>
              </div>
            )}

          </div>

          {/* ── Submit ───────────────────────────────────── */}
          <div className="px-4 pt-4 pb-8 mt-2 sticky bottom-0 bg-gradient-to-t from-slate-900 via-slate-900/95 to-transparent">
            <Button
              type="submit"
              disabled={isSubmitting || isCreatingCash || saved}
              className={cn(
                "w-full h-12 rounded-xl font-semibold text-base shadow-lg transition-all active:scale-[0.98]",
                saved
                  ? "bg-emerald-600 shadow-emerald-600/25"
                  : cfg.submit
              )}
            >
              {saved ? (
                <span className="flex items-center gap-2">
                  <Check className="h-5 w-5" />
                  Saved!
                </span>
              ) : isSubmitting ? "Saving…" : isEdit ? "Save Changes" : `Add ${cfg.label}`}
            </Button>
          </div>

        </form>
      </SheetContent>
    </Sheet>
  );
}
