import { db } from "@/db";
import { bankAccounts, categories } from "@/db/schema";
import { eq } from "drizzle-orm";
import { requireHousehold } from "@/lib/session";
import { loadLedger } from "@/lib/ledger-service";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { LedgerTable } from "./ledger-table";
import { addMonths, startOfMonth, endOfMonth } from "date-fns";

export default async function LedgerPage({
  searchParams,
}: {
  searchParams: Promise<{ account?: string; range?: string }>;
}) {
  const sp = await searchParams;
  const { householdId } = await requireHousehold();

  const accts = await db.select().from(bankAccounts).where(eq(bankAccounts.householdId, householdId));
  const cats = await db.select().from(categories).where(eq(categories.householdId, householdId));

  const today = new Date();
  const months = sp.range === "12" ? 12 : sp.range === "6" ? 6 : sp.range === "1" ? 1 : 3;
  const from = startOfMonth(today);
  const to = endOfMonth(addMonths(today, months - 1));

  const { rows } = await loadLedger({
    householdId,
    from,
    to,
    bankAccountId: sp.account || undefined,
  });

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Ledger</h1>
        <p className="text-sm text-muted-foreground">
          Posted transactions plus everything projected from your recurring rules.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Cashflow</CardTitle>
          <CardDescription>
            Showing {rows.length} rows. Projected rows are dashed — click ✓ to post.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <LedgerTable
            rows={rows}
            accounts={accts}
            categories={cats}
            selectedAccountId={sp.account}
            range={String(months)}
          />
        </CardContent>
      </Card>
    </div>
  );
}
