// ---------------------------------------------------------------------------
// SP30: "Recent batches" Dashboard widget.
//
// One row per batch the operator parsed recently. Each row tells the
// operator two things at a glance:
//   1. Was this batch clean or did it have a problem? (icon tint +
//      `topRejectionReason` line under the filename when present.)
//   2. What was the billed-out outcome? ($ for 837P; payment count for
//      835 ERA batches — the Remittance table has no batch-level
//      `total_charge` aggregate.)
//
// Click → onRowClick(id) so the page can navigate to /batches?batch=ID
// (the BatchDrawer deep-link pattern from pages/Batches.tsx).
//
// Reuses the Dashboard "Recent activity" card chrome verbatim (Card +
// CardHeader pb-3 + CardTitle text-[14px] + CardContent pt-0) so the
// widget reads as part of the same family.
// ---------------------------------------------------------------------------

import { Layers, CheckCircle2, AlertTriangle } from "lucide-react";
import type { KeyboardEvent } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { fmt } from "@/lib/format";
import type { BatchSummary } from "@/lib/api";
import { cn } from "@/lib/utils";

type Props = {
  batches: BatchSummary[];
  onRowClick: (batchId: string) => void;
  /** Cap shown in the header subtitle. Default 5. */
  limit?: number;
};

export function RecentBatchesWidget({ batches, onRowClick, limit = 5 }: Props) {
  return (
    <Card data-testid="recent-batches-widget">
      <CardHeader className="flex flex-row items-start justify-between space-y-0 pb-3">
        <div>
          <CardTitle className="flex items-center gap-2 text-[14px]">
            <Layers className="h-3.5 w-3.5 text-muted-foreground" strokeWidth={1.75} />
            Recent batches
          </CardTitle>
          <p className="text-xs text-muted-foreground mt-1">
            How the last {limit} batches billed out — sorted newest first.
          </p>
        </div>
        <span className="mono text-[10.5px] uppercase tracking-[0.14em] text-muted-foreground">
          {batches.length} latest
        </span>
      </CardHeader>
      <CardContent className="pt-0">
        {batches.length === 0 ? (
          <div
            className="text-[13px] text-muted-foreground px-2 py-6 text-center"
            data-testid="recent-batches-empty"
          >
            No batches yet.
          </div>
        ) : (
          <ul className="divide-y divide-border/40">
            {batches.map((b) => {
              const rejected = b.rejectedCount ?? 0;
              const clean = !b.hasProblem && rejected === 0;
              const tint = clean
                ? "hsl(var(--success))"
                : "hsl(var(--destructive))";
              const Icon = clean ? CheckCircle2 : AlertTriangle;
              const ariaLabel = clean
                ? `Clean batch ${b.inputFilename || b.id}`
                : `Batch with rejections ${b.inputFilename || b.id}`;
              return (
                <BatchRow
                  key={b.id}
                  batch={b}
                  tint={tint}
                  Icon={Icon}
                  ariaLabel={ariaLabel}
                  onActivate={() => onRowClick(b.id)}
                />
              );
            })}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}

// ---------------------------------------------------------------------------
// BatchRow — one row in the widget. Kept as a separate component so the
// parent can stay readable; matches the clickable-row + keyboard
// accessibility pattern from Dashboard.tsx:300-307 and the divide-y
// row markup from ActivityFeed.tsx:124-140.
// ---------------------------------------------------------------------------
type BatchRowProps = {
  batch: BatchSummary;
  tint: string;
  Icon: typeof CheckCircle2;
  ariaLabel: string;
  onActivate: () => void;
};

function BatchRow({ batch, tint, Icon, ariaLabel, onActivate }: BatchRowProps) {
  function onKeyDown(e: KeyboardEvent<HTMLLIElement>) {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      onActivate();
    }
  }
  const isErn = batch.kind === "835";
  const accepted = batch.acceptedCount ?? 0;
  const billed = batch.billedTotal ?? 0;
  return (
    <li
      role="button"
      tabIndex={0}
      aria-label={ariaLabel}
      data-testid={`recent-batch-row-${batch.id}`}
      onClick={onActivate}
      onKeyDown={onKeyDown}
      className={cn(
        "drillable flex items-center gap-3 py-3 cursor-pointer",
        "hover:bg-muted/30 transition-colors",
      )}
    >
      <div
        aria-hidden
        className="mt-0.5 h-7 w-7 shrink-0 rounded-md ring-1 ring-inset ring-border/40 flex items-center justify-center"
        style={{ color: tint }}
      >
        <Icon className="h-3.5 w-3.5" strokeWidth={1.75} />
      </div>
      <div className="flex-1 min-w-0">
        <div className="text-[13px] font-medium text-foreground/95 truncate">
          {batch.inputFilename || batch.id}
        </div>
        <div className="mono text-[10.5px] text-muted-foreground mt-0.5 flex items-center gap-2 min-w-0">
          <span className="shrink-0">{batch.kind.toUpperCase()}</span>
          <span aria-hidden className="shrink-0">·</span>
          <span className="shrink-0">{fmt.relative(batch.parsedAt)}</span>
          {batch.topRejectionReason && (
            <>
              <span aria-hidden className="shrink-0">·</span>
              <span
                className="truncate"
                style={{ color: "hsl(var(--destructive))" }}
                data-testid="recent-batch-rejection"
              >
                {batch.topRejectionReason}
              </span>
            </>
          )}
        </div>
      </div>
      <div className="text-right shrink-0">
        {isErn ? (
          <>
            <div className="display mono text-[15px] tabular-nums text-foreground">
              {fmt.num(batch.claimCount)}
            </div>
            <div className="mono text-[10.5px] text-muted-foreground">payments</div>
          </>
        ) : (
          <>
            <div
              className="display mono text-[15px] tabular-nums text-foreground"
              data-testid="recent-batch-billed"
            >
              {fmt.usd(billed)}
            </div>
            <div className="mono text-[10.5px] text-muted-foreground">
              {fmt.num(accepted)}/{fmt.num(batch.claimCount)} accepted
            </div>
          </>
        )}
      </div>
    </li>
  );
}