import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

export type StatusTone = "success" | "warning" | "error" | "info" | "neutral";

export const TONE_CLASS: Record<StatusTone, string> = {
  success: "border-status-success-border bg-status-success-bg text-status-success-text",
  warning: "border-status-warning-border bg-status-warning-bg text-status-warning-text",
  error: "border-status-error-border bg-status-error-bg text-status-error-text",
  info: "border-status-info-border bg-status-info-bg text-status-info-text",
  neutral: "border-border bg-muted text-muted-foreground",
};

/** One typed map for every record status in Medora: domain -> label -> tone. */
export const STATUS_MAP = {
  sale: { Paid: "success", Held: "warning", Credit: "info", Returned: "error" },
  stock: { "In stock": "success", Low: "warning", Out: "error", Expired: "error" },
  // Expired: the API marks prescriptions past their validity (Customers conversion, 25 Oct 2026)
  prescription: { Pending: "warning", Dispensed: "success", Partially: "info", Cancelled: "neutral", Expired: "neutral" },
  purchaseOrder: { Pending: "warning", Received: "success", Partial: "info", Cancelled: "neutral" },
  shift: { Open: "info", Closed: "neutral" },
  user: { Active: "success", Disabled: "neutral" },
} as const satisfies Record<string, Record<string, StatusTone>>;

export type StatusDomain = keyof typeof STATUS_MAP;
export type StatusLabel<D extends StatusDomain> = Extract<keyof (typeof STATUS_MAP)[D], string>;

export function RecordStatusBadge<D extends StatusDomain>({
  domain,
  status,
  className,
}: {
  domain: D;
  status: StatusLabel<D>;
  className?: string;
}) {
  const tone = (STATUS_MAP[domain] as Record<string, StatusTone>)[status];
  return (
    <Badge variant="outline" className={cn("rounded-md", TONE_CLASS[tone], className)}>
      {status}
    </Badge>
  );
}

export type RoleName = "Admin" | "Pharmacist" | "Cashier";
const ROLE_CLASS: Record<RoleName, string> = {
  Admin: "border-primary/30 bg-accent text-accent-foreground",
  Pharmacist: "border-status-info-border bg-status-info-bg text-status-info-text",
  Cashier: "border-border bg-muted text-foreground",
};

/** Role is identity, not state, so it uses teal, blue and grey rather than the status colours. */
export function RoleBadge({ role, className }: { role: RoleName; className?: string }) {
  return (
    <Badge variant="outline" className={cn("rounded-md", ROLE_CLASS[role], className)}>
      {role}
    </Badge>
  );
}
