import { db } from "@/db";
import { savingsGoals } from "@/db/schema";
import { eq } 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 { Trash2 } from "lucide-react";
import { addGoalAction, deleteGoalAction } from "./actions";
import { InterestCalculator } from "./calculator";

export default async function GoalsPage() {
  const { householdId } = await requireHousehold();
  const goals = await db.select().from(savingsGoals).where(eq(savingsGoals.householdId, householdId));

  return (
    <div className="space-y-6 max-w-6xl mx-auto">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Goals & calculator</h1>
        <p className="text-sm text-muted-foreground">
          Set savings targets and project growth with compound interest.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>Add savings goal</CardTitle>
          </CardHeader>
          <CardContent>
            <form action={addGoalAction} className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1.5 sm:col-span-2">
                <Label>Name</Label>
                <Input name="name" required placeholder="House deposit" />
              </div>
              <div className="space-y-1.5">
                <Label>Target amount</Label>
                <Input name="targetAmount" type="number" step="0.01" required placeholder="20000" />
              </div>
              <div className="space-y-1.5">
                <Label>Current saved</Label>
                <Input name="currentAmount" type="number" step="0.01" placeholder="0" />
              </div>
              <div className="space-y-1.5">
                <Label>Target date</Label>
                <Input name="targetDate" type="date" />
              </div>
              <div className="space-y-1.5">
                <Label>Monthly contribution</Label>
                <Input name="monthlyContribution" type="number" step="0.01" placeholder="400" />
              </div>
              <div className="space-y-1.5 sm:col-span-2">
                <Label>Annual interest rate (%)</Label>
                <Input name="annualInterestRatePct" type="number" step="0.01" placeholder="4.5" />
              </div>
              <div className="sm:col-span-2">
                <Button type="submit" className="w-full">Add goal</Button>
              </div>
            </form>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Compound interest calculator</CardTitle>
            <CardDescription>Project a savings amount over time</CardDescription>
          </CardHeader>
          <CardContent>
            <InterestCalculator />
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Your goals</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {goals.length === 0 ? (
            <p className="text-sm text-muted-foreground">None yet — add one above.</p>
          ) : goals.map((g) => {
            const pct = Math.min(100, Math.round((g.currentAmountMinor / g.targetAmountMinor) * 100));
            return (
              <div key={g.id} className="space-y-1.5">
                <div className="flex items-center justify-between text-sm">
                  <div className="font-medium">{g.name}</div>
                  <div className="flex items-center gap-3">
                    <div className="font-mono tabular text-sm">
                      {formatMoney(g.currentAmountMinor)}
                      <span className="text-muted-foreground"> / {formatMoney(g.targetAmountMinor)}</span>
                    </div>
                    <form action={deleteGoalAction}>
                      <input type="hidden" name="id" value={g.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} />
                <div className="text-xs text-muted-foreground">
                  {g.monthlyContributionMinor > 0 ? `${formatMoney(g.monthlyContributionMinor)}/mo` : "No monthly contribution set"}
                  {g.annualInterestRate > 0 ? ` · ${(g.annualInterestRate / 100).toFixed(2)}% APR` : ""}
                  {g.targetDate ? ` · target ${g.targetDate}` : ""}
                </div>
              </div>
            );
          })}
        </CardContent>
      </Card>
    </div>
  );
}
