import type { ReactNode } from "react";

import { cn } from "@/lib/utils";
import type { ColumnFormat } from "@/pages/ruleEngine/config/resources";
import { Badge } from "@edr/ui-common";

const statusBadgeClass = (active: boolean) =>
  cn(
    "rounded-sm px-2 py-0.5 text-xs font-medium",
    active
      ? "border-emerald-200 bg-emerald-50 text-emerald-800"
      : "border-border bg-muted text-muted-foreground",
  );

export const formatCell = (value: unknown, format?: ColumnFormat): ReactNode => {
  if (value === null || value === undefined || value === "") {
    return <span className="text-muted-foreground">—</span>;
  }

  if (format === "boolean") {
    return value ? "Yes" : "No";
  }

  if (format === "activeBadge") {
    const active = Boolean(value);
    return (
      <Badge variant="outline" className={statusBadgeClass(active)}>
        {active ? "Active" : "Inactive"}
      </Badge>
    );
  }

  if (format === "rateStatus") {
    const status = String(value);
    const tone =
      status === "LIVE"
        ? "border-emerald-200 bg-emerald-50 text-emerald-800"
        : status === "DRAFT"
          ? "border-amber-200 bg-amber-50 text-amber-800"
          : "border-sky-200 bg-sky-50 text-sky-800";
    return (
      <Badge variant="outline" className={cn("rounded-sm font-medium", tone)}>
        {status}
      </Badge>
    );
  }

  if (format === "code") {
    return (
      <Badge
        variant="secondary"
        className="rounded-sm border border-border bg-muted/80 font-mono text-[11px] font-medium text-foreground"
      >
        {String(value)}
      </Badge>
    );
  }

  if (format === "date") {
    const d = new Date(String(value));
    return Number.isNaN(d.getTime()) ? String(value) : d.toLocaleDateString();
  }

  return String(value);
};
