import type { ReactNode } from "react";
import { Badge, Text } from "@mantine/core";

import type { ColumnFormat } from "@/pages/ruleEngine/config/resources";
import { formatCell as formatRuleEngineCell } from "@/components/ruleEngine/ruleEngineFormat";

export type FleetColumnFormat = ColumnFormat | "statusBadge";

const optionLabelMap = new Map<string, Map<string, string>>();

export const registerFleetOptionLabels = (
  fieldKey: string,
  options: { value: string; label: string }[],
) => {
  optionLabelMap.set(fieldKey, new Map(options.map((o) => [o.value, o.label])));
};

export const formatFleetCell = (
  value: unknown,
  format?: FleetColumnFormat,
  accessorKey?: string,
): ReactNode => {
  console.log('formatFleetCell:', { value, format, accessorKey, type: typeof value });

  if (format === "statusBadge") {
    const status = value == null || value === "" ? "—" : String(value);
    const getStatusColor = (st: string): string => {
      const s = st.toUpperCase();
      if (s === "ACTIVE") return "green";
      if (s === "INACTIVE") return "gray";
      if (s === "SUSPENDED" || s === "OUT_OF_SERVICE") return "red";
      if (s === "MAINTENANCE" || s === "ON_LEAVE") return "orange";
      if (s === "RETIRED") return "gray";
      return "gray";
    };
    return (
      <Badge variant="light" color={getStatusColor(status)} size="sm" radius="md">
        {status}
      </Badge>
    );
  }

  if (accessorKey && optionLabelMap.has(accessorKey)) {
    const label = optionLabelMap.get(accessorKey)?.get(String(value ?? ""));
    if (label) {
      return <Text size="sm">{label}</Text>;
    }
  }

  const result = formatRuleEngineCell(value, format as ColumnFormat | undefined);
  console.log('formatRuleEngineCell result for', accessorKey, ':', result);
  return result;
};
