import { ArrowRight } from "lucide-react";
import { Badge, type BadgeProps } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { fmt } from "@/lib/format";
import type { ClaimDetail } from "@/types";

type MatchedRemitCardProps = {
  matchedRemittance: ClaimDetail["matchedRemittance"];
};

/**
 * Remittance status → Badge variant. Mirrors the list-endpoint mapping
 * in ``RemittanceStatus`` (received / posted / reconciled). Unknown
 * statuses (the type is an unconstrained string) fall back to ``muted``
 * so a future backend status doesn't blow up the drawer.
 */
const STATUS_VARIANT: Record<string, BadgeProps["variant"]> = {
  received: "secondary",
  posted: "default",
  reconciled: "success",
};

function statusVariantFor(status: string): BadgeProps["variant"] {
  return STATUS_VARIANT[status] ?? "muted";
}

/**
 * Matched-remittance card for the claim detail drawer (SP4).
 *
 * Renders only when the claim has been paired with an ERA (the
 * ``matchedRemittance`` field is non-null). Layout: a single card with
 * remit id + status badge + received date on the left, big mono
 * ``totalPaid`` on the right, plus a "View remittance →" link that
 * deep-links to ``/remittances?id={id}`` (v1: full page navigation via
 * ``window.location.href``; a router-based nav handler is a v2 concern).
 */
export function MatchedRemitCard({ matchedRemittance }: MatchedRemitCardProps) {
  if (matchedRemittance === null) return null;

  const { id, totalPaid, status, receivedAt } = matchedRemittance;
  // SP7: per-line counts may be missing on pre-SP7 claim-detail responses.
  const matchedLines = matchedRemittance.matchedLines;
  const totalLines = matchedRemittance.totalLines;
  const hasLineCounts =
    typeof matchedLines === "number" && typeof totalLines === "number";
  const allMatched = hasLineCounts && matchedLines === totalLines;

  const handleViewRemittance = () => {
    window.location.href = `/remittances?id=${id}`;
  };

  return (
    <section
      className="flex flex-col gap-3 px-6 py-4"
      data-testid="matched-remit-card"
    >
      <h3
        data-testid="section-label"
        className="eyebrow text-muted-foreground"
      >
        Matched Remittance
      </h3>

      <div
        data-testid="matched-remit-card-inner"
        className="flex flex-col gap-4 rounded-lg border border-border/60 bg-muted/30 p-4 sm:flex-row sm:items-start sm:justify-between"
      >
        {/* Left: remit id + status badge + received date */}
        <div className="flex min-w-0 flex-col gap-2">
          <span
            data-testid="matched-remit-id"
            className="mono text-sm text-foreground"
          >
            {id}
          </span>
          <div className="flex flex-wrap items-center gap-2">
            <Badge
              variant={statusVariantFor(status)}
              data-testid="matched-remit-status"
              className="uppercase tracking-[0.14em]"
            >
              {status}
            </Badge>
            <span
              data-testid="matched-remit-received"
              className="text-xs text-muted-foreground"
            >
              Received {fmt.date(receivedAt)}
            </span>
          </div>
        </div>

        {/* Right: total paid + view-remittance link */}
        <div className="flex flex-col items-start gap-2 sm:items-end">
          <span
            data-testid="matched-remit-total-paid"
            className="display text-3xl text-foreground tabular-nums"
          >
            {fmt.usdPrecise(totalPaid)}
          </span>
          <Button
            variant="ghost"
            size="sm"
            onClick={handleViewRemittance}
            data-testid="view-remittance-link"
            className="gap-1 text-muted-foreground hover:text-foreground"
          >
            View remittance
            <ArrowRight
              className="h-3.5 w-3.5"
              strokeWidth={1.75}
              aria-hidden
            />
          </Button>
        </div>
      </div>

      {hasLineCounts ? (
        <span
          data-testid="matched-remit-line-counts"
          data-all-matched={allMatched ? "true" : "false"}
          className="mono text-xs uppercase tracking-[0.14em]"
          style={{ color: allMatched ? "var(--tt-amber)" : "var(--tt-oxblood)" }}
        >
          lines: {matchedLines}/{totalLines} matched
          {!allMatched ? ` (${totalLines! - matchedLines!} unmatched)` : null}
        </span>
      ) : null}
    </section>
  );
}
