import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import { formatShortMonthDayEST } from "@/lib/timezoneUtils";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import {
  DollarSign, TrendingUp, TrendingDown, Wallet, Receipt, RefreshCw,
  ArrowUpRight, ArrowDownRight, FileText, CreditCard, BarChart3,
  Download, PieChart, ChevronRight, Calendar, Building2, Printer
} from "lucide-react";
import { generateFinancialOverviewPdf } from "@/lib/financialOverviewPdf";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import {
  BarChart, Bar, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, PieChart as RePieChart, Pie, Cell, Legend, Area, AreaChart
} from "recharts";

// ─── Helpers ──────────────────────────────────────────────────────────
const fmt = (n: number) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(n);
const fmtFull = (n: number) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(n);

const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const CHART_COLORS = [
  "hsl(224, 76%, 53%)", // primary blue
  "hsl(142, 71%, 45%)", // success green
  "hsl(38, 92%, 50%)",  // warning amber
  "hsl(0, 72%, 51%)",   // destructive red
  "hsl(262, 52%, 47%)", // purple
  "hsl(199, 89%, 48%)", // cyan
  "hsl(25, 95%, 53%)",  // orange
  "hsl(340, 75%, 55%)", // pink
];

// ─── Component ────────────────────────────────────────────────────────
export default function BoardFinancialOverviewView({ boardAssociationIds }: { boardAssociationIds?: string[] } = {}) {
  const { toast } = useToast();
  const navigate = useNavigate();
  const isBoardScoped = Array.isArray(boardAssociationIds) && boardAssociationIds.length > 0;
  const [loading, setLoading] = useState(true);
  const [associations, setAssociations] = useState<any[]>([]);
  const [selectedAssocId, setSelectedAssocId] = useState<string>(isBoardScoped && boardAssociationIds!.length === 1 ? boardAssociationIds![0] : "all");

  // Raw data
  const [bankAccounts, setBankAccounts] = useState<any[]>([]);
  const [ledgerEntries, setLedgerEntries] = useState<any[]>([]);
  const [bills, setBills] = useState<any[]>([]);
  const [transactions, setTransactions] = useState<any[]>([]);
  const [collections, setCollections] = useState<any[]>([]);
  const [owners, setOwners] = useState<any[]>([]);


  // ─── Data Loading ────────────────────────────────────────────────
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      // Build queries — when board-scoped, restrict everything to the board's associations
      const assocQ = supabase
        .from("associations")
        .select("id, name, logo_url")
        .eq("status", "active")
        .order("name");
      if (isBoardScoped) assocQ.in("id", boardAssociationIds!);

      const bankQ = supabase.from("bank_accounts").select("*").eq("status", "active");
      if (isBoardScoped) bankQ.in("association_id", boardAssociationIds!);

      const ledgerQ = supabase.from("owner_ledger_entries").select("*").order("date", { ascending: false }).limit(1000);
      if (isBoardScoped) ledgerQ.in("association_id", boardAssociationIds!);

      const billsQ = supabase.from("bills").select("*").order("bill_date", { ascending: false }).limit(500);
      if (isBoardScoped) billsQ.in("association_id", boardAssociationIds!);

      const txQ = supabase.from("bank_transactions").select("*").order("date", { ascending: false }).limit(200);
      if (isBoardScoped) txQ.in("association_id", boardAssociationIds!);

      const colQ = supabase.from("collections").select("id, owner_id, association_id, status, amount_owed, created_at");
      if (isBoardScoped) colQ.in("association_id", boardAssociationIds!);

      const ownersQ = supabase.from("owners").select("id, first_name, last_name, balance, association_id").eq("status", "active");
      if (isBoardScoped) ownersQ.in("association_id", boardAssociationIds!);

      const [assocRes, bankRes, ledgerRes, billsRes, txRes, colRes, ownersRes] = await Promise.all([
        assocQ, bankQ, ledgerQ, billsQ, txQ, colQ, ownersQ,
      ]);

      if (assocRes.data) setAssociations(assocRes.data);
      if (bankRes.data) setBankAccounts(bankRes.data);
      if (ledgerRes.data) setLedgerEntries(ledgerRes.data);
      if (billsRes.data) setBills(billsRes.data);
      if (txRes.data) setTransactions(txRes.data);
      if (colRes.data) setCollections(colRes.data);
      if (ownersRes.data) setOwners(ownersRes.data);
    } catch (err: any) {
      console.error(err);
      toast({ variant: "destructive", title: "Error", description: "Failed to load financial data." });
    } finally {
      setLoading(false);
    }
  }, [toast, isBoardScoped, boardAssociationIds]);

  useEffect(() => { fetchData(); }, [fetchData]);


  // ─── Filtered Data ───────────────────────────────────────────────
  const filterByAssoc = useCallback((items: any[]) => {
    if (selectedAssocId === "all") return items;
    return items.filter(i => i.association_id === selectedAssocId);
  }, [selectedAssocId]);

  // ─── Metric Calculations ─────────────────────────────────────────
  const metrics = useMemo(() => {
    const filteredBanks = filterByAssoc(bankAccounts);
    const filteredOwners = filterByAssoc(owners);
    const filteredBills = filterByAssoc(bills);

    const operatingBalance = filteredBanks
      .filter((a) => a.account_category === "operating")
      .reduce((s, a) => s + (a.current_balance || 0), 0);
    const reserveBalance = filteredBanks
      .filter((a) => a.account_category === "reserve")
      .reduce((s, a) => s + (a.current_balance || 0), 0);
    const accountsReceivable = filteredOwners
      .filter((o) => (o.balance || 0) > 0)
      .reduce((s, o) => s + (o.balance || 0), 0);
    const accountsPayable = filteredBills.filter(b => b.status === "pending" || b.status === "approved").reduce((s, b) => s + ((b.amount || 0) - (b.amount_paid || 0)), 0);

    return { operatingBalance, reserveBalance, accountsReceivable, accountsPayable };
  }, [bankAccounts, owners, bills, filterByAssoc]);

  // ─── Monthly Income vs Expenses Chart ────────────────────────────
  const monthlyChart = useMemo(() => {
    const filtered = filterByAssoc(ledgerEntries);
    const now = new Date();
    const year = now.getFullYear();

    const data = MONTHS.map((month, idx) => {
      const monthEntries = filtered.filter(e => {
        const d = new Date(e.date);
        return d.getFullYear() === year && d.getMonth() === idx;
      });
      const income = monthEntries.reduce((s, e) => s + (e.credit || 0), 0);
      const expenses = monthEntries.reduce((s, e) => s + (e.debit || 0), 0);
      return { month, income, expenses };
    });

    return data;
  }, [ledgerEntries, filterByAssoc]);

  // ─── Delinquency Trend ───────────────────────────────────────────
  const delinquencyTrend = useMemo(() => {
    const filtered = filterByAssoc(collections);
    const now = new Date();

    return Array.from({ length: 6 }, (_, i) => {
      const d = new Date(now.getFullYear(), now.getMonth() - (5 - i), 1);
      const monthEnd = new Date(d.getFullYear(), d.getMonth() + 1, 0);
      const active = filtered.filter(c => {
        const created = new Date(c.created_at);
        return created <= monthEnd && c.status !== "resolved";
      });
      return {
        month: MONTHS[d.getMonth()],
        accounts: active.length,
        amount: active.reduce((s, c) => s + (c.amount_owed || 0), 0),
      };
    });
  }, [collections, filterByAssoc]);

  // ─── Expense Categories Pie ──────────────────────────────────────
  const expenseCategories = useMemo(() => {
    const filtered = filterByAssoc(ledgerEntries).filter(e => (e.debit || 0) > 0);
    const cats: Record<string, number> = {};
    filtered.forEach(e => {
      const type = e.transaction_type || "Other";
      const label = type.charAt(0).toUpperCase() + type.slice(1).replace(/_/g, " ");
      cats[label] = (cats[label] || 0) + (e.debit || 0);
    });
    return Object.entries(cats)
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 8);
  }, [ledgerEntries, filterByAssoc]);

  // ─── Recent Transactions ─────────────────────────────────────────
  const recentTransactions = useMemo(() => {
    return filterByAssoc(transactions).slice(0, 10);
  }, [transactions, filterByAssoc]);

  // ─── Quick Actions ────────────────────────────────────────────────
  const quickActions = isBoardScoped
    ? [
        { label: "View Reports", icon: BarChart3, path: "/homeowner/board/financial-reports", color: "text-amber-600" },
      ]
    : [
        { label: "Create Invoice", icon: FileText, path: "/dashboard/client-invoices", color: "text-primary" },
        { label: "Record Payment", icon: CreditCard, path: "/dashboard/payments", color: "text-emerald-600" },
        { label: "Run Report", icon: BarChart3, path: "/dashboard/financial-reports", color: "text-amber-600" },
        { label: "Export Financials", icon: Download, path: "/dashboard/reports", color: "text-purple-600" },
      ];

  // ─── Print PDF ────────────────────────────────────────────────────
  const [printing, setPrinting] = useState(false);
  const handlePrintPdf = async () => {
    setPrinting(true);
    try {
      const selectedAssoc = associations.find((a) => a.id === selectedAssocId) || null;
      const scopeLabel =
        selectedAssocId === "all"
          ? "All Associations"
          : selectedAssoc?.name || "Selected Association";
      await generateFinancialOverviewPdf({
        association: selectedAssoc,
        scopeLabel,
        metrics: {
          ...metrics,
          arAccounts: filterByAssoc(owners).filter((o) => (o.balance || 0) > 0).length,
          apPending: filterByAssoc(bills).filter((b) => b.status === "pending").length,
        },
        monthly: monthlyChart,
        categories: expenseCategories,
        delinquency: delinquencyTrend,
        transactions: recentTransactions,
      });
    } catch (err: any) {
      console.error(err);
      toast({ variant: "destructive", title: "Export failed", description: err?.message || "Could not generate PDF." });
    } finally {
      setPrinting(false);
    }
  };

  // ─── Print Visual (charts) ────────────────────────────────────────
  const visualRef = useRef<HTMLDivElement | null>(null);
  const [printingVisual, setPrintingVisual] = useState(false);
  const handlePrintVisual = async () => {
    if (!visualRef.current) return;
    setPrintingVisual(true);
    try {
      const [{ default: html2canvas }, { default: jsPDF }] = await Promise.all([
        import("html2canvas"),
        import("jspdf"),
      ]);
      // Allow charts to settle
      await new Promise((r) => setTimeout(r, 300));
      const node = visualRef.current;
      const canvas = await html2canvas(node, {
        scale: 2,
        useCORS: true,
        backgroundColor: "#ffffff",
        windowWidth: node.scrollWidth,
      });
      const pdf = new jsPDF({ unit: "pt", format: "letter", orientation: "landscape" });
      const pageW = pdf.internal.pageSize.getWidth();
      const pageH = pdf.internal.pageSize.getHeight();
      const margin = 24;
      const usableW = pageW - margin * 2;
      const ratio = usableW / canvas.width;
      const fullH = canvas.height * ratio;

      const selectedAssoc = associations.find((a) => a.id === selectedAssocId) || null;
      const scopeLabel =
        selectedAssocId === "all" ? "All Associations" : selectedAssoc?.name || "Selected Association";

      const drawHeader = () => {
        pdf.setFont("helvetica", "bold");
        pdf.setFontSize(13);
        pdf.text("Financial Overview", margin, 28);
        pdf.setFont("helvetica", "normal");
        pdf.setFontSize(10);
        pdf.setTextColor(110);
        pdf.text(scopeLabel, margin, 44);
        pdf.text(
          new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }),
          pageW - margin,
          44,
          { align: "right" },
        );
        pdf.setTextColor(0);
      };

      const headerH = 56;
      const contentH = pageH - headerH - margin;
      // Slice canvas into pages
      const sliceHpx = contentH / ratio; // px of source per page
      let y = 0;
      let page = 0;
      while (y < canvas.height) {
        if (page > 0) pdf.addPage();
        drawHeader();
        const h = Math.min(sliceHpx, canvas.height - y);
        const slice = document.createElement("canvas");
        slice.width = canvas.width;
        slice.height = h;
        const ctx = slice.getContext("2d")!;
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, slice.width, slice.height);
        ctx.drawImage(canvas, 0, y, canvas.width, h, 0, 0, canvas.width, h);
        const imgData = slice.toDataURL("image/jpeg", 0.92);
        pdf.addImage(imgData, "JPEG", margin, headerH, usableW, h * ratio, undefined, "FAST");
        y += h;
        page += 1;
      }
      const fileName = `${(selectedAssoc?.name || scopeLabel).replace(/[^a-z0-9]+/gi, "_")}_Financial_Overview_Visual_${new Date().toISOString().slice(0, 10)}.pdf`;
      pdf.save(fileName);
    } catch (err: any) {
      console.error(err);
      toast({ variant: "destructive", title: "Visual export failed", description: err?.message || "Could not generate visual PDF." });
    } finally {
      setPrintingVisual(false);
    }
  };

  // ─── Custom Tooltip ───────────────────────────────────────────────
  const ChartTooltip = ({ active, payload, label }: any) => {
    if (!active || !payload?.length) return null;
    return (
      <div className="bg-card border rounded-lg shadow-lg p-3 text-sm">
        <p className="font-medium text-foreground mb-1">{label}</p>
        {payload.map((p: any, i: number) => (
          <div key={i} className="flex items-center gap-2">
            <div className="h-2 w-2 rounded-full" style={{ backgroundColor: p.color }} />
            <span className="text-muted-foreground">{p.name}:</span>
            <span className="font-medium text-foreground">{fmtFull(p.value)}</span>
          </div>
        ))}
      </div>
    );
  };

  // ─── Render ──────────────────────────────────────────────────────
  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* ── Header ─────────────────────────────────────────────────── */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Wallet className="h-6 w-6 text-primary" /> Financial Overview
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            Association financial health at a glance.
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Select value={selectedAssocId} onValueChange={setSelectedAssocId}>
            <SelectTrigger className="w-[220px]">
              <Building2 className="h-4 w-4 mr-2 text-muted-foreground" />
              <SelectValue placeholder={isBoardScoped && associations.length === 1 ? associations[0]?.name : "All Associations"} />
            </SelectTrigger>
            <SelectContent>
              {(!isBoardScoped || associations.length > 1) && (
                <SelectItem value="all">All Associations</SelectItem>
              )}
              {associations.map(a => (
                <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button variant="outline" size="sm" onClick={fetchData}>
            <RefreshCw className="h-4 w-4 mr-2" /> Refresh
          </Button>
          <Button size="sm" onClick={handlePrintPdf} disabled={printing}>
            <Printer className="h-4 w-4 mr-2" /> {printing ? "Generating…" : "Print PDF"}
          </Button>
          <Button size="sm" variant="outline" onClick={handlePrintVisual} disabled={printingVisual}>
            <BarChart3 className="h-4 w-4 mr-2" /> {printingVisual ? "Capturing…" : "Print Visual"}
          </Button>
        </div>
      </div>

      <div ref={visualRef} className="space-y-6 bg-background">
      {/* ── Top Metrics ────────────────────────────────────────────── */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <MetricCard
          title="Operating Balance"
          value={fmt(metrics.operatingBalance)}
          icon={<Wallet className="h-5 w-5" />}
          trend={metrics.operatingBalance >= 0 ? "positive" : "negative"}
          iconBg="bg-primary/10 text-primary"
        />
        <MetricCard
          title="Reserve Balance"
          value={fmt(metrics.reserveBalance)}
          icon={<DollarSign className="h-5 w-5" />}
          trend="neutral"
          iconBg="bg-emerald-500/10 text-emerald-600"
        />
        <MetricCard
          title="Accounts Receivable"
          value={fmt(metrics.accountsReceivable)}
          icon={<TrendingUp className="h-5 w-5" />}
          trend={metrics.accountsReceivable > 0 ? "warning" : "positive"}
          subtitle={`${filterByAssoc(owners).filter((o) => (o.balance || 0) > 0).length} accounts`}
          iconBg="bg-amber-500/10 text-amber-600"
        />
        <MetricCard
          title="Accounts Payable"
          value={fmt(metrics.accountsPayable)}
          icon={<Receipt className="h-5 w-5" />}
          trend="neutral"
          subtitle={`${filterByAssoc(bills).filter(b => b.status === "pending").length} pending`}
          iconBg="bg-purple-500/10 text-purple-600"
        />
      </div>

      {/* ── Charts Row ──────────────────────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Income vs Expenses */}
        <Card className="lg:col-span-2">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm font-semibold text-foreground">Income vs Expenses</CardTitle>
              <div className="flex items-center gap-4 text-xs text-muted-foreground">
                <span className="flex items-center gap-1.5">
                  <span className="h-2 w-2 rounded-full bg-primary" /> Income
                </span>
                <span className="flex items-center gap-1.5">
                  <span className="h-2 w-2 rounded-full bg-destructive/70" /> Expenses
                </span>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="h-[260px]">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={monthlyChart} barGap={2}>
                  <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" vertical={false} />
                  <XAxis dataKey="month" tickLine={false} axisLine={false} tick={{ fill: "hsl(215, 16%, 47%)", fontSize: 12 }} />
                  <YAxis tickLine={false} axisLine={false} tick={{ fill: "hsl(215, 16%, 47%)", fontSize: 12 }} tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} />
                  <Tooltip content={<ChartTooltip />} />
                  <Bar dataKey="income" name="Income" fill="hsl(224, 76%, 53%)" radius={[4, 4, 0, 0]} maxBarSize={28} />
                  <Bar dataKey="expenses" name="Expenses" fill="hsl(0, 72%, 51%, 0.7)" radius={[4, 4, 0, 0]} maxBarSize={28} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        {/* Expense Categories */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-semibold text-foreground">Expense Categories</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[260px]">
              {expenseCategories.length > 0 ? (
                <ResponsiveContainer width="100%" height="100%">
                  <RePieChart>
                    <Pie
                      data={expenseCategories}
                      cx="50%"
                      cy="45%"
                      innerRadius={50}
                      outerRadius={80}
                      paddingAngle={2}
                      dataKey="value"
                    >
                      {expenseCategories.map((_, i) => (
                        <Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(v: number) => fmtFull(v)} />
                    <Legend
                      layout="horizontal"
                      verticalAlign="bottom"
                      iconType="circle"
                      iconSize={8}
                      formatter={(value: string) => (
                        <span className="text-xs text-muted-foreground">{value}</span>
                      )}
                    />
                  </RePieChart>
                </ResponsiveContainer>
              ) : (
                <div className="flex items-center justify-center h-full text-sm text-muted-foreground">
                  No expense data available
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* ── Delinquency Trend ───────────────────────────────────────── */}
      <Card>
        <CardHeader className="pb-2">
          <div className="flex items-center justify-between">
            <CardTitle className="text-sm font-semibold text-foreground">Delinquency Trend (6 Months)</CardTitle>
            <div className="flex items-center gap-4 text-xs text-muted-foreground">
              <span className="flex items-center gap-1.5">
                <span className="h-2 w-2 rounded-full bg-destructive" /> Amount
              </span>
              <span className="flex items-center gap-1.5">
                <span className="h-2 w-2 rounded-full bg-amber-500" /> Accounts
              </span>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="h-[200px]">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={delinquencyTrend}>
                <defs>
                  <linearGradient id="delinqGradient" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="hsl(0, 72%, 51%)" stopOpacity={0.2} />
                    <stop offset="100%" stopColor="hsl(0, 72%, 51%)" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" vertical={false} />
                <XAxis dataKey="month" tickLine={false} axisLine={false} tick={{ fill: "hsl(215, 16%, 47%)", fontSize: 12 }} />
                <YAxis yAxisId="amount" tickLine={false} axisLine={false} tick={{ fill: "hsl(215, 16%, 47%)", fontSize: 12 }} tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`} />
                <YAxis yAxisId="count" orientation="right" tickLine={false} axisLine={false} tick={{ fill: "hsl(215, 16%, 47%)", fontSize: 12 }} />
                <Tooltip content={<ChartTooltip />} />
                <Area yAxisId="amount" type="monotone" dataKey="amount" name="Amount" stroke="hsl(0, 72%, 51%)" fill="url(#delinqGradient)" strokeWidth={2} />
                <Line yAxisId="count" type="monotone" dataKey="accounts" name="Accounts" stroke="hsl(38, 92%, 50%)" strokeWidth={2} dot={{ r: 3, fill: "hsl(38, 92%, 50%)" }} />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* ── Bottom Row: Transactions + Quick Actions ─────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
        {/* Recent Transactions */}
        <Card className="lg:col-span-3 overflow-hidden">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm font-semibold text-foreground">Recent Transactions</CardTitle>
              <Button variant="ghost" size="sm" className="text-xs text-muted-foreground" onClick={() => navigate("/dashboard/payments")}>
                View All <ChevronRight className="h-3 w-3 ml-1" />
              </Button>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {recentTransactions.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/30">
                    <TableHead className="text-xs">Date</TableHead>
                    <TableHead className="text-xs">Description</TableHead>
                    <TableHead className="text-xs">Type</TableHead>
                    <TableHead className="text-xs text-right">Amount</TableHead>
                    <TableHead className="text-xs text-center">Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {recentTransactions.map(tx => {
                    const isCredit = (tx.credit || 0) > 0;
                    const amount = isCredit ? tx.credit : tx.debit;
                    return (
                      <TableRow key={tx.id} className="text-sm">
                        <TableCell className="py-2.5">
                          <span className="text-muted-foreground">{formatShortMonthDayEST(tx.date)}</span>
                        </TableCell>
                        <TableCell className="py-2.5">
                          <span className="font-medium text-foreground truncate block max-w-[280px]">
                            {tx.description || "Transaction"}
                          </span>
                        </TableCell>
                        <TableCell className="py-2.5">
                          <Badge variant="outline" className="text-[10px] font-medium">
                            {(tx.transaction_type || "other").replace(/_/g, " ")}
                          </Badge>
                        </TableCell>
                        <TableCell className="py-2.5 text-right">
                          <span className={`font-semibold ${isCredit ? "text-emerald-600" : "text-foreground"}`}>
                            {isCredit ? "+" : "-"}{fmtFull(amount || 0)}
                          </span>
                        </TableCell>
                        <TableCell className="py-2.5 text-center">
                          <Badge
                            className={`text-[10px] border-0 ${
                              tx.is_cleared
                                ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
                                : "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400"
                            }`}
                          >
                            {tx.is_cleared ? "Cleared" : "Pending"}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            ) : (
              <div className="py-12 text-center text-sm text-muted-foreground">
                No recent transactions found.
              </div>
            )}
          </CardContent>
        </Card>

        {/* Quick Actions */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-semibold text-foreground">Quick Actions</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            {quickActions.map(action => (
              <button
                key={action.label}
                onClick={() => navigate(action.path)}
                className="w-full flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 transition-colors text-left group"
              >
                <div className={`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${action.color} group-hover:scale-105 transition-transform`}>
                  <action.icon className="h-4 w-4" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-foreground">{action.label}</p>
                </div>
                <ChevronRight className="h-4 w-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
              </button>
            ))}
          </CardContent>
        </Card>
      </div>
      </div>
    </div>
  );
}

// ─── Metric Card ──────────────────────────────────────────────────────
function MetricCard({ title, value, icon, trend, subtitle, iconBg }: {
  title: string;
  value: string;
  icon: React.ReactNode;
  trend: "positive" | "negative" | "warning" | "neutral";
  subtitle?: string;
  iconBg: string;
}) {
  return (
    <Card className="relative overflow-hidden">
      <CardContent className="p-5">
        <div className="flex items-start justify-between">
          <div className="space-y-1">
            <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">{title}</p>
            <p className={`text-2xl font-bold ${
              trend === "negative" ? "text-destructive" :
              trend === "warning" ? "text-amber-600" :
              trend === "positive" ? "text-emerald-600" :
              "text-foreground"
            }`}>
              {value}
            </p>
            {subtitle && <p className="text-xs text-muted-foreground">{subtitle}</p>}
          </div>
          <div className={`h-10 w-10 rounded-xl flex items-center justify-center ${iconBg}`}>
            {icon}
          </div>
        </div>
      </CardContent>
      {/* Subtle accent bar */}
      <div className={`absolute bottom-0 left-0 right-0 h-0.5 ${
        trend === "negative" ? "bg-destructive/40" :
        trend === "warning" ? "bg-amber-500/40" :
        trend === "positive" ? "bg-emerald-500/40" :
        "bg-primary/20"
      }`} />
    </Card>
  );
}
