import { Link } from "@tanstack/react-router";
import { ArrowDownLeft, ArrowUpRight, ChevronRight } from "lucide-react";
import { formatDate, txTypeLabel } from "@/lib/format";
import { Money } from "@/components/Money";
import { cn } from "@/lib/utils";

type Tx = {
  id: string;
  type: string;
  status: string;
  amount: number | string;
  reference: string;
  external_reference?: string | null;
  description?: string | null;
  created_at: string;
  metadata?: unknown;
};

const CREDIT_TYPES = new Set(["funding", "transfer_in", "referral_bonus", "admin_credit", "reversal", "cashback"]);

/** Tappable transaction row — opens the full receipt/details page. */
export function TransactionItem({ tx }: { tx: Tx }) {
  const isCredit = CREDIT_TYPES.has(tx.type);
  const Icon = isCredit ? ArrowDownLeft : ArrowUpRight;
  return (
    <li>
      <Link
        to="/app/tx/$ref"
        params={{ ref: tx.reference }}
        className="flex items-center gap-3 rounded-xl bg-card p-3 shadow-card transition hover:bg-muted/40 active:scale-[0.995]"
      >
        <div className={cn(
          "grid h-10 w-10 shrink-0 place-items-center rounded-full",
          isCredit ? "bg-success/15 text-success" : "bg-primary/10 text-primary",
        )}>
          <Icon className="h-5 w-5" />
        </div>
        <div className="min-w-0 flex-1">
          <div className="truncate text-sm font-medium">{txTypeLabel[tx.type] ?? tx.type}</div>
          <div className="truncate text-xs text-muted-foreground">{tx.description ?? tx.reference}</div>
          <div className="text-[10px] text-muted-foreground">{formatDate(tx.created_at)}</div>
        </div>
        <div className="text-right">
          <div className={cn("text-sm font-semibold", isCredit ? "text-success" : "text-foreground")}>
            {isCredit ? "+" : "-"}<Money value={tx.amount} />
          </div>
          <div className={cn(
            "text-[10px] font-medium uppercase",
            tx.status === "success" ? "text-success"
              : tx.status === "failed" ? "text-destructive"
              : "text-warning",
          )}>{tx.status}</div>
        </div>
        <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
      </Link>
    </li>
  );
}
