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" | "verifiedBadge";

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 => {
  if (format === "verifiedBadge") {
    return value === true ? (
      <Badge variant="light" color="green" size="sm" radius="md">
        Verified
      </Badge>
    ) : (
      <Text size="sm" c="dimmed">—</Text>
    );
  }

  if (format === "statusBadge") {
    const status = value == null || value === "" ? "—" : String(value);
    const getStatusColor = (st: string): string => {
      const s = st.toUpperCase();
      if (s === "ACTIVE" || s === "AVAILABLE") return "green";
      if (s === "FREE") return "teal";
      if (s === "BUSY") return "blue";
      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" || s === "DETAINED") return "gray";
      return "gray";
    };
    const color = getStatusColor(status);
    return (
      <Badge variant="light" color={color} 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>;
    }
  }

  return formatRuleEngineCell(value, format as ColumnFormat | undefined);
};
