import * as React from "react";
import Link from "next/link";
import { ArrowDownRight, ArrowUpRight, type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";

const TONE: Record<string, string> = {
  blue: "bg-blue-600/10 text-blue-600",
  cyan: "bg-cyan-500/10 text-cyan-600 dark:text-cyan-400",
  emerald: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
  amber: "bg-amber-500/10 text-amber-600 dark:text-amber-400",
  rose: "bg-rose-500/10 text-rose-600 dark:text-rose-400",
};

/** Dense KPI tile for the admin dashboard. */
export function AdminStatCard({
  label,
  value,
  sub,
  icon: Icon,
  tone = "blue",
  delta,
  href,
}: {
  label: string;
  value: React.ReactNode;
  sub?: React.ReactNode;
  icon: LucideIcon;
  tone?: keyof typeof TONE | string;
  /** "+18%" / "-4%" — the sign drives the colour and arrow. */
  delta?: string;
  href?: string;
}) {
  const negative = Boolean(delta && delta.trim().startsWith("-"));
  const body = (
    <>
      <div className="flex items-start justify-between gap-2">
        <span className="text-[11px] font-medium tracking-wider text-muted-foreground uppercase">
          {label}
        </span>
        <span
          className={cn(
            "grid size-7 shrink-0 place-items-center rounded-lg",
            TONE[tone] ?? TONE.blue,
          )}
        >
          <Icon className="size-4" />
        </span>
      </div>
      <div className="mt-1.5 font-mono text-xl font-semibold tracking-tight tabular-nums">
        {value}
      </div>
      <div className="mt-0.5 flex items-center gap-1.5 text-xs text-muted-foreground">
        {delta ? (
          <span
            className={cn(
              "inline-flex items-center gap-0.5 font-medium",
              negative
                ? "text-rose-600 dark:text-rose-400"
                : "text-emerald-600 dark:text-emerald-400",
            )}
          >
            {negative ? (
              <ArrowDownRight className="size-3" />
            ) : (
              <ArrowUpRight className="size-3" />
            )}
            {delta}
          </span>
        ) : null}
        {sub ? <span className="truncate">{sub}</span> : null}
      </div>
    </>
  );

  const className =
    "rounded-2xl border bg-card p-3 shadow-sm transition-colors hover:border-blue-600/30";

  return href ? (
    <Link href={href} className={cn(className, "block")}>
      {body}
    </Link>
  ) : (
    <div className={className}>{body}</div>
  );
}

export default AdminStatCard;
