import { clsx } from "clsx";

type Tone =
  | "neutral"
  | "info"
  | "success"
  | "warning"
  | "danger"
  | "muted"
  | "accent";

const toneClasses: Record<Tone, string> = {
  neutral:
    "bg-[var(--color-line)] text-[var(--color-ink)] ring-1 ring-inset ring-[var(--color-line)]",
  info:
    "bg-[var(--color-mist)] text-[var(--color-blue)] ring-1 ring-inset ring-[var(--color-mist)]",
  success:
    "bg-emerald-50 text-emerald-700 ring-1 ring-inset ring-emerald-200",
  warning:
    "bg-amber-50 text-amber-800 ring-1 ring-inset ring-amber-200",
  danger:
    "bg-red-50 text-red-700 ring-1 ring-inset ring-red-200",
  muted:
    "bg-white text-[var(--color-slate)] ring-1 ring-inset ring-[var(--color-line)]",
  accent:
    "bg-[var(--color-blue)] text-white ring-1 ring-inset ring-[var(--color-blue)]",
};

const statusToneMap: Record<string, Tone> = {
  pending: "info",
  approved: "success",
  active: "success",
  published: "success",
  live: "success",
  rejected: "danger",
  archived: "muted",
  draft: "warning",
  suspended: "danger",
  closed: "muted",
  paused: "warning",
  inactive: "muted",
  "out-of-stock": "danger",
  "in-stock": "success",
  enrolling: "info",
  completed: "success",
  user: "neutral",
  admin: "accent",
};

type Props = {
  label: string;
  tone?: Tone;
  /** Override label display but keep tone lookup by `label`. */
  display?: string;
  dot?: boolean;
  className?: string;
};

export function StatusBadge({ label, tone, display, dot, className }: Props) {
  const resolvedTone: Tone = tone ?? statusToneMap[label.toLowerCase()] ?? "neutral";
  const text = (display ?? label).replace(/-/g, " ");
  return (
    <span
      className={clsx(
        "inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider",
        toneClasses[resolvedTone],
        className,
      )}
    >
      {dot && (
        <span
          aria-hidden
          className={clsx(
            "h-1.5 w-1.5 rounded-full",
            resolvedTone === "success" && "bg-emerald-500",
            resolvedTone === "danger" && "bg-red-500",
            resolvedTone === "warning" && "bg-amber-500",
            resolvedTone === "info" && "bg-[var(--color-blue)]",
            resolvedTone === "accent" && "bg-white",
            (resolvedTone === "neutral" || resolvedTone === "muted") &&
              "bg-[var(--color-slate)]",
          )}
        />
      )}
      {text}
    </span>
  );
}
