import { useRouter } from "@tanstack/react-router";
import { toast } from "sonner";
import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { acceptHeldGift, type GiftTrackingRow } from "@/lib/server/api-donations";
import { moneyCents } from "@/lib/utils";

export function CflGiftTracking({ rows }: { rows: GiftTrackingRow[] }) {
  const router = useRouter();
  const [busy, setBusy] = useState<string | null>(null);
  const held = rows.filter((r) => r.status === "held");

  async function accept(id: string) {
    setBusy(id);
    try {
      const res = await acceptHeldGift({ data: { id } });
      toast.success(res.already ? "Already in Layer 4." : "Verified. Booked as one Layer 4 gift with a receipt.");
      await router.invalidate();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not accept.");
    } finally {
      setBusy(null);
    }
  }

  return (
    <Card className="mb-6">
      <CardContent className="pt-5">
        <p className="text-[11px] font-medium tracking-[0.18em] text-primary uppercase">CFL gift tracking</p>
        <h2 className="mt-1 font-display text-xl">Held by DonorBox webhook security</h2>
        <p className="mt-2 max-w-3xl text-sm text-navy">
          Unsigned or mis-signed DonorBox payloads never become Layer 4. They land here so Super Admin can still see
          that someone tried to give. Verify the money, then accept — that books one gift. Duplicates from DonorBox
          retries share one fingerprint.
        </p>
        {rows.length === 0 ? (
          <p className="mt-3 text-sm text-navy">Nothing held. Signed webhooks go straight to Layer 4.</p>
        ) : (
          <ul className="mt-4 space-y-2">
            {rows.map((r) => (
              <li key={r.id} className="flex flex-wrap items-center justify-between gap-3 rounded-lg bg-muted/60 px-3 py-3">
                <div>
                  <p className="text-sm font-semibold text-navy">{r.donor_name ?? "Unknown sender"}</p>
                  <p className="text-xs text-navy">
                    {r.amount_cents ? moneyCents(r.amount_cents) : "no amount"} · {r.campaign ?? "uncategorized"} · {r.reason}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant={r.status === "held" ? "warning" : r.status === "accepted" ? "success" : "muted"}>
                    {r.status}
                  </Badge>
                  {r.status === "held" ? (
                    <Button size="sm" variant="gold" disabled={busy === r.id} onClick={() => void accept(r.id)}>
                      {busy === r.id ? "Booking…" : "Accept into Layer 4"}
                    </Button>
                  ) : null}
                </div>
              </li>
            ))}
          </ul>
        )}
        {held.length > 0 ? (
          <p className="mt-3 text-xs text-navy">{held.length} held. Not in gifts-this-quarter until you accept.</p>
        ) : null}
      </CardContent>
    </Card>
  );
}