import { db } from "@/db";
import { bankAccounts, transactions } from "@/db/schema";
import { and, eq } from "drizzle-orm";
import { requireHousehold } from "@/lib/session";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { loadLedger } from "@/lib/ledger-service";
import { addMonths, format, startOfMonth } from "date-fns";
import { ForecastChart } from "./forecast-chart";

export default async function ForecastPage() {
  const { householdId } = await requireHousehold();
  const today = new Date();
  const horizonEnd = addMonths(today, 12);

  const accts = await db.select().from(bankAccounts).where(and(eq(bankAccounts.householdId, householdId), eq(bankAccounts.isArchived, false)));

  // Today's total balance
  let totalToday = 0;
  for (const a of accts) {
    const txs = await db
      .select()
      .from(transactions)
      .where(and(eq(transactions.bankAccountId, a.id), eq(transactions.householdId, householdId), eq(transactions.status, "posted")));
    const sum = txs.reduce((s, t) => s + t.amountMinor, 0);
    totalToday += a.openingBalanceMinor + sum;
  }

  const { rows } = await loadLedger({ householdId, from: startOfMonth(today), to: horizonEnd });
  const future = rows.filter((r) => r.date >= today.toISOString().slice(0, 10));

  // Monthly snapshot of total balance after the last txn that month
  const months: { label: string; date: string; balance: number; deltaMonth: number }[] = [];
  let running = totalToday;
  for (let i = 0; i < 12; i++) {
    const monthStart = startOfMonth(addMonths(today, i));
    const monthEnd = startOfMonth(addMonths(today, i + 1));
    const monthIso = monthStart.toISOString().slice(0, 10);
    const nextIso = monthEnd.toISOString().slice(0, 10);
    const monthTxs = future.filter((r) => r.date >= monthIso && r.date < nextIso);
    const delta = monthTxs.reduce((s, r) => s + r.amountMinor, 0);
    running += delta;
    months.push({
      label: format(monthStart, "MMM yy"),
      date: monthIso,
      balance: running,
      deltaMonth: delta,
    });
  }

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Forecast</h1>
        <p className="text-sm text-muted-foreground">
          Projected total balance across all accounts based on your recurring rules. Adjust the sliders to see what-ifs.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Next 12 months</CardTitle>
          <CardDescription>Starting at {new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" }).format(totalToday / 100)} today</CardDescription>
        </CardHeader>
        <CardContent>
          <ForecastChart months={months} startBalance={totalToday} />
        </CardContent>
      </Card>
    </div>
  );
}
