import { db } from "@/db";
import { bankAccounts } 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 { Label } from "@/components/ui/label";
import { importCsvAction } from "./actions";

export default async function ImportPage() {
  const { householdId } = await requireHousehold();
  const accts = await db.select().from(bankAccounts).where(eq(bankAccounts.householdId, householdId));

  return (
    <div className="space-y-6 max-w-4xl mx-auto">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Import CSV</h1>
        <p className="text-sm text-muted-foreground">
          Paste a CSV with headers like <code className="font-mono text-xs">date, description, in, out</code>{" "}
          (or <code className="font-mono text-xs">amount</code>). Rows are imported as posted transactions.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Paste CSV</CardTitle>
          <CardDescription>From your spreadsheet — copy the rows including the header.</CardDescription>
        </CardHeader>
        <CardContent>
          <form action={importCsvAction} className="space-y-3">
            <div className="space-y-1.5">
              <Label>Target account</Label>
              <select name="bankAccountId" required className="h-9 w-full rounded-md border bg-input/40 px-2 text-sm">
                {accts.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
              </select>
            </div>
            <div className="space-y-1.5">
              <Label>CSV</Label>
              <textarea
                name="csv"
                required
                rows={14}
                className="w-full rounded-md border bg-input/40 p-3 text-sm font-mono"
                placeholder="date,description,in,out&#10;May 9th,Netflix,,10.00&#10;May 11th,Weekly Rent,,400.00"
              />
            </div>
            <Button type="submit">Import</Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
