import { db } from "@/db";
import { budgets, categories, transactions } from "@/db/schema";
import { and, eq, gte, lte } from "drizzle-orm";
import { requireHousehold } from "@/lib/session";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { formatMoney } from "@/lib/utils";
import { addBudgetAction, deleteBudgetAction } from "./actions";
import { startOfMonth, endOfMonth } from "date-fns";
import { Trash2 } from "lucide-react";

export default async function BudgetsPage() {
  const { householdId } = await requireHousehold();
  const today = new Date();
  const cats = await db.select().from(categories).where(eq(categories.householdId, householdId));
  const all = await db.select().from(budgets).where(eq(budgets.householdId, householdId));
  const monthStartIso = startOfMonth(today).toISOString().slice(0, 10);
  const monthEndIso = endOfMonth(today).toISOString().slice(0, 10);
  const txs = await db
    .select()
    .from(transactions)
    .where(
      and(
        eq(transactions.householdId, householdId),
        eq(transactions.status, "posted"),
        gte(transactions.date, monthStartIso),
        lte(transactions.date, monthEndIso),
      ),
    );

  const spent: Record<string, number> = {};
  for (const t of txs) {
    if (!t.categoryId || t.amountMinor >= 0) continue;
    spent[t.categoryId] = (spent[t.categoryId] ?? 0) + Math.abs(t.amountMinor);
  }

  const expenseCats = cats.filter((c) => c.kind === "expense");

  return (
    <div className="space-y-6 max-w-5xl mx-auto">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Budgets</h1>
        <p className="text-sm text-muted-foreground">Set spending caps per category. Monthly progress is computed from posted transactions.</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>New budget</CardTitle>
        </CardHeader>
        <CardContent>
          <form action={addBudgetAction} className="grid grid-cols-1 sm:grid-cols-[1fr_140px_140px_auto] gap-3 items-end">
            <div className="space-y-1.5">
              <Label>Category</Label>
              <select name="categoryId" required className="h-9 w-full rounded-md border bg-input/40 px-2 text-sm">
                {expenseCats.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div className="space-y-1.5">
              <Label>Amount</Label>
              <Input name="amount" type="number" step="0.01" required placeholder="400.00" />
            </div>
            <div className="space-y-1.5">
              <Label>Period</Label>
              <select name="period" defaultValue="monthly" className="h-9 w-full rounded-md border bg-input/40 px-2 text-sm">
                <option value="weekly">Weekly</option>
                <option value="monthly">Monthly</option>
                <option value="yearly">Yearly</option>
              </select>
            </div>
            <Button type="submit">Add</Button>
          </form>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>This month</CardTitle>
          <CardDescription>{all.length} budgets configured</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {all.length === 0 ? (
            <p className="text-sm text-muted-foreground">No budgets yet.</p>
          ) : all.map((b) => {
            const cat = cats.find((c) => c.id === b.categoryId);
            const used = spent[b.categoryId] ?? 0;
            const pct = Math.round((used / b.amountMinor) * 100);
            const over = used > b.amountMinor;
            return (
              <div key={b.id} className="space-y-1.5">
                <div className="flex items-center justify-between text-sm">
                  <div className="font-medium flex items-center gap-2">
                    {cat?.name ?? "Category"}
                    <span className="text-xs text-muted-foreground capitalize">{b.period}</span>
                  </div>
                  <div className="flex items-center gap-3">
                    <div className="font-mono tabular text-sm">
                      <span className={over ? "text-destructive" : ""}>{formatMoney(used)}</span>
                      <span className="text-muted-foreground"> / {formatMoney(b.amountMinor)}</span>
                    </div>
                    <form action={deleteBudgetAction}>
                      <input type="hidden" name="id" value={b.id} />
                      <Button type="submit" variant="ghost" size="icon" className="text-muted-foreground hover:text-destructive">
                        <Trash2 className="size-4" />
                      </Button>
                    </form>
                  </div>
                </div>
                <Progress value={pct} className={over ? "[&>div]:bg-destructive" : ""} />
              </div>
            );
          })}
        </CardContent>
      </Card>
    </div>
  );
}
