import type { InboxClaimRow, InboxCandidateRow, ScoreBreakdown } from "@/lib/inbox-api";
import { cn } from "@/lib/utils";

export type Accent = "oxblood" | "amber" | "ink-blue" | "muted";

const ACCENT_VAR: Record<Accent, string> = {
  oxblood: "var(--tt-oxblood)",
  amber: "var(--tt-amber)",
  "ink-blue": "var(--tt-ink-blue)",
  muted: "var(--tt-muted)",
};

function fmtMoney(n: number | null | undefined): string {
  if (n == null) return "—";
  return n.toLocaleString("en-US", { style: "currency", currency: "USD" });
}

function fmtAgo(iso: string | null | undefined): string {
  if (!iso) return "";
  const ms = Date.now() - new Date(iso).getTime();
  if (Number.isNaN(ms)) return "";
  const mins = Math.round(ms / 60_000);
  if (mins < 60) return `${mins}m`;
  const hrs = Math.round(mins / 60);
  if (hrs < 24) return `${hrs}h`;
  const days = Math.round(hrs / 24);
  return `${days}d`;
}

function Sparkline({ breakdown }: { breakdown: ScoreBreakdown | null }) {
  if (!breakdown) return null;
  const fields: Array<keyof ScoreBreakdown> = ["patient", "date", "amount", "provider"];
  return (
    <span className="inline-flex items-end gap-[2px] align-middle h-3.5">
      {fields.map((k) => {
        const v = breakdown[k] as number;
        const h = Math.max(3, Math.round(v * 14));
        return (
          <span
            key={k}
            title={`${k}: ${v.toFixed(2)}`}
            className={cn(
              "inline-block w-[3px] rounded-[1px] transition-all",
              v >= 0.7
                ? "bg-[color:var(--tt-amber)] shadow-[0_0_4px_-1px_var(--tt-amber)]"
                : v >= 0.5
                  ? "bg-[color:var(--tt-amber)]/70"
                  : "bg-[color:var(--tt-muted)]"
            )}
            style={{ height: `${h}px` }}
          />
        );
      })}
    </span>
  );
}

type Props =
  | { row: InboxClaimRow; accent: Accent; onClick: () => void }
  | { row: InboxCandidateRow; accent: Accent; onClick: () => void };

export function InboxRow({ row, accent, onClick }: Props) {
  const isCandidate = row.kind === "remit";
  const id = isCandidate ? (row as InboxCandidateRow).payer_claim_control_number : row.id;
  const payer = (isCandidate ? (row as InboxCandidateRow).payer_id : (row as InboxClaimRow).payer_id) ?? "";
  const charge = fmtMoney(row.charge_amount);
  const reason = !isCandidate ? (row as InboxClaimRow).rejection_reason : null;
  const rejectedAt = !isCandidate ? (row as InboxClaimRow).rejected_at : null;
  const topScore = isCandidate && row.candidates.length > 0 ? row.candidates[0].score : null;
  const filled = isCandidate && row.candidates.length > 0 ? row.candidates[0].breakdown : null;

  return (
    <tr
      onClick={onClick}
      className="cursor-pointer transition-colors group"
    >
      <td
        aria-hidden
        style={{
          width: 4,
          background: ACCENT_VAR[accent],
          padding: 0,
          boxShadow: `inset 0 0 0 1px ${ACCENT_VAR[accent]}40`,
        }}
      />
      <td
        className="py-2.5 pl-3 mono font-semibold"
        style={{ color: "var(--tt-ink)", fontSize: 12, letterSpacing: "-0.005em" }}
      >
        {id}
      </td>
      <td
        className="py-2.5 mono"
        style={{ color: reason ? "var(--tt-oxblood)" : "var(--tt-amber)", fontSize: 11 }}
      >
        {reason ?? (topScore != null ? `score ${topScore}` : "")}
      </td>
      <td
        className="py-2.5 mono tabular-nums"
        style={{ color: "var(--tt-ink-dim)", fontSize: 11 }}
      >
        {fmtAgo(rejectedAt)}
      </td>
      <td
        className="py-2.5 text-right mono tabular-nums font-semibold"
        style={{ color: "var(--tt-ink)", fontSize: 12 }}
      >
        {charge}
      </td>
      <td
        className="py-2.5 pl-4 mono uppercase"
        style={{ color: "var(--tt-ink-dim)", fontSize: 10, letterSpacing: "0.14em" }}
      >
        {payer}
      </td>
      <td className="py-2.5 pr-3">
        <Sparkline breakdown={filled} />
      </td>
    </tr>
  );
}
