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-[color:var(--m-ink-tertiary)]"
      >
        Matched Remittance
      </h3>

      <div
        data-testid="matched-remit-card-inner"
        className="flex flex-col gap-4 rounded-lg border border-[color:var(--m-border-heavy)]/30 bg-[color:var(--m-surface)]/60 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-[color:var(--m-ink-primary)]"
          >
            {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-[color:var(--m-ink-tertiary)]"
            >
              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-[color:var(--m-ink-primary)] tabular-nums"
          >
            {fmt.usdPrecise(totalPaid)}
          </span>
          <Button
            variant="ghost"
            size="sm"
            onClick={handleViewRemittance}
            data-testid="view-remittance-link"
            className="gap-1 text-[color:var(--m-ink-secondary)] hover:text-[color:var(--m-ink-primary)]"
          >
            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>
  );
}
