import { db } from "@/db";
import { recurringRules, bankAccounts, categories } 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 { Badge } from "@/components/ui/badge";
import { formatMoney } from "@/lib/utils";
import { addRuleAction, deleteRuleAction, toggleRuleAction } from "./actions";
import { RRULE_PRESETS } from "@/lib/recurring";
import { Pause, Play, Trash2 } from "lucide-react";

export default async function RecurringPage() {
  const { householdId } = await requireHousehold();
  const rules = await db.select().from(recurringRules).where(eq(recurringRules.householdId, householdId));
  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 acctMap = new Map(accts.map((a) => [a.id, a]));
  const catMap = new Map(cats.map((c) => [c.id, c]));
  const today = new Date().toISOString().slice(0, 10);

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Recurring rules</h1>
        <p className="text-sm text-muted-foreground">
          Set it once. The ledger and forecasts use these to project the future.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>New rule</CardTitle>
          <CardDescription>Use a negative amount for an expense, positive for income.</CardDescription>
        </CardHeader>
        <CardContent>
          <form action={addRuleAction} className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            <div className="space-y-1.5 lg:col-span-2">
              <Label>Description</Label>
              <Input name="description" required placeholder="Weekly Rent" />
            </div>
            <div className="space-y-1.5">
              <Label>Amount</Label>
              <Input name="amount" type="number" step="0.01" required placeholder="-262.00" />
            </div>
            <div className="space-y-1.5">
              <Label>Account</Label>
              <select name="bankAccountId" className="h-9 w-full rounded-md border bg-input/40 px-2 text-sm" required>
                {accts.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
              </select>
            </div>
            <div className="space-y-1.5">
              <Label>Category</Label>
              <select name="categoryId" className="h-9 w-full rounded-md border bg-input/40 px-2 text-sm">
                <option value="">— None —</option>
                {cats.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div className="space-y-1.5">
              <Label>Schedule</Label>
              <select name="rrule" className="h-9 w-full rounded-md border bg-input/40 px-2 text-sm">
                {RRULE_PRESETS.map((p) => <option key={p.rrule} value={p.rrule}>{p.label}</option>)}
              </select>
            </div>
            <div className="space-y-1.5">
              <Label>Start date</Label>
              <Input name="startDate" type="date" defaultValue={today} required />
            </div>
            <div className="space-y-1.5">
              <Label>End date (optional)</Label>
              <Input name="endDate" type="date" />
            </div>
            <div className="flex items-end">
              <Button type="submit" className="w-full">Add rule</Button>
            </div>
          </form>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Active rules</CardTitle>
          <CardDescription>{rules.length} configured</CardDescription>
        </CardHeader>
        <CardContent className="space-y-2">
          {rules.length === 0 ? (
            <p className="text-sm text-muted-foreground">None yet.</p>
          ) : rules.map((r) => (
            <div key={r.id} className="flex items-center justify-between rounded-md border bg-card/40 px-4 py-3">
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <span className="font-medium truncate">{r.description}</span>
                  {!r.isActive && <Badge variant="secondary">Paused</Badge>}
                </div>
                <div className="text-xs text-muted-foreground truncate">
                  {acctMap.get(r.bankAccountId)?.name}
                  {r.categoryId ? ` · ${catMap.get(r.categoryId)?.name}` : ""}
                  {" · "}{prettyRRule(r.rrule)}
                </div>
              </div>
              <div className={`font-mono tabular mr-3 ${r.amountMinor < 0 ? "text-destructive" : "text-success"}`}>
                {formatMoney(r.amountMinor)}
              </div>
              <form action={toggleRuleAction} className="mr-1">
                <input type="hidden" name="id" value={r.id} />
                <input type="hidden" name="isActive" value={String(r.isActive)} />
                <Button type="submit" variant="ghost" size="icon">
                  {r.isActive ? <Pause className="size-4" /> : <Play className="size-4" />}
                </Button>
              </form>
              <form action={deleteRuleAction}>
                <input type="hidden" name="id" value={r.id} />
                <Button type="submit" variant="ghost" size="icon" className="text-muted-foreground hover:text-destructive">
                  <Trash2 className="size-4" />
                </Button>
              </form>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}

function prettyRRule(rrule: string): string {
  const map: Record<string, string> = {
    "FREQ=DAILY": "Daily",
    "FREQ=WEEKLY;BYDAY=MO": "Weekly · Mon",
    "FREQ=WEEKLY;BYDAY=FR": "Weekly · Fri",
    "FREQ=WEEKLY;INTERVAL=2": "Every 2 weeks",
    "FREQ=MONTHLY": "Monthly",
    "FREQ=MONTHLY;BYMONTHDAY=1": "Monthly · 1st",
    "FREQ=MONTHLY;BYMONTHDAY=-1": "Monthly · last day",
    "FREQ=YEARLY": "Yearly",
  };
  return map[rrule] ?? rrule;
}
