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

import type { ColumnFormat } from "@/pages/ruleEngine/config/resources";

const extractLabel = (value: unknown): string | null => {
  if (!value || typeof value !== "object") return null;

  const obj = value as Record<string, unknown>;
  return (
    (typeof obj.label === "string" ? obj.label : null) ||
    (typeof obj.cargoTypeName === "string" ? obj.cargoTypeName : null) ||
    (typeof obj.code === "string" ? obj.code : null) ||
    (typeof obj.name === "string" ? obj.name : null) ||
    (typeof obj.actionLabel === "string" ? obj.actionLabel : null) ||
    null
  );
};

export const formatCell = (
  value: unknown,
  format?: ColumnFormat,
  // The row the cell came from — currency amounts read their code off it so a
  // last-mile rate priced in birr does not render as USD.
  row?: Record<string, unknown>,
): ReactNode => {
  if (value === null || value === undefined || value === "") {
    return <Text size="sm" c="dimmed">—</Text>;
  }

  // Handle stringified objects (e.g., "[object Object]")
  if (typeof value === "string" && value.trim() === "[object Object]") {
    return <Text size="sm" c="dimmed">—</Text>;
  }

  if (format === "boolean") {
    if (typeof value === "string") {
      const boolVal = value.toLowerCase() === "true" || value === "1";
      return <Text size="sm">{boolVal ? "✓ Yes" : "✗ No"}</Text>;
    }
    return <Text size="sm">{value ? "✓ Yes" : "✗ No"}</Text>;
  }

  if (format === "activeBadge") {
    const active = Boolean(value);
    return (
      <Badge
        color={active ? "edr-green" : "gray"}
        variant={active ? "filled" : "light"}
        size="sm"
        radius="md"
      >
        {active ? "Active" : "Inactive"}
      </Badge>
    );
  }

  if (format === "rateStatus") {
    const status = String(value);
    const color =
      status === "LIVE"
        ? "edr-green"
        : status === "DRAFT"
          ? "yellow"
          : status === "PENDING_APPROVAL"
            ? "orange"
            : "blue";
    return (
      <Badge color={color} variant="filled" size="sm" radius="md">
        {status}
      </Badge>
    );
  }

  if (format === "validityBadge") {
    const status = String(value);
    const label =
      status === "VALID" ? "Valid" : status === "EXPIRED" ? "Expired" : "Not started";
    const color =
      status === "VALID" ? "edr-green" : status === "EXPIRED" ? "red" : "yellow";
    return (
      <Badge color={color} variant="filled" size="sm" radius="md">
        {label}
      </Badge>
    );
  }

  if (format === "code") {
    return (
      <Badge
        variant="light"
        color="blue"
        size="sm"
        radius="md"
        style={{
          fontFamily: "monospace",
          fontSize: "0.75rem",
          fontWeight: 600,
          letterSpacing: "0.05em",
        }}
      >
        {String(value).toUpperCase()}
      </Badge>
    );
  }

  if (format === "text") {
    return <Text size="sm">{String(value)}</Text>;
  }

  if (format === "number") {
    const num = Number(value);
    return <Text size="sm">{Number.isNaN(num) ? String(value) : num.toLocaleString()}</Text>;
  }

  if (format === "currency") {
    const num = Number(value);
    const code = typeof row?.currency === "string" ? row.currency : "USD";
    return (
      <Text size="sm" fw={500}>
        {Number.isNaN(num) ? String(value) : `${code} ${num.toLocaleString()}`}
      </Text>
    );
  }

  if (format === "date") {
    const d = new Date(String(value));
    if (Number.isNaN(d.getTime())) return <Text size="sm">{String(value)}</Text>;
    return <Text size="sm">{d.toLocaleDateString()}</Text>;
  }

  if (Array.isArray(value)) {
    return (
      <Text size="sm">{value.length > 0 ? value.join(", ") : "—"}</Text>
    );
  }

  if (format === "entityLabel" && value && typeof value === "object") {
    const label = extractLabel(value);
    if (label) {
      return <Text size="sm">{label}</Text>;
    }
    return <Text size="sm" c="dimmed">—</Text>;
  }

  if (format === "rateLabel") {
    if (!value || typeof value !== "object") {
      return value ? (
        <Text size="sm" c="dimmed" style={{ fontFamily: "monospace" }}>
          {String(value)}
        </Text>
      ) : (
        <Text size="sm" c="dimmed">—</Text>
      );
    }
    const rate = value as {
      rateType?: string;
      currency?: string;
      rateValue?: number;
      rateUnit?: string;
    };
    const parts = [
      rate.rateType?.replace(/_/g, " "),
      rate.currency,
      rate.rateValue != null ? String(rate.rateValue) : "",
      rate.rateUnit?.replace(/_/g, " "),
    ].filter(Boolean);
    return parts.length > 0 ? (
      <Text size="sm">{parts.join(" · ")}</Text>
    ) : (
      <Text size="sm" c="dimmed">—</Text>
    );
  }

  if (typeof value === "object") {
    const label = extractLabel(value);
    if (label) return <Text size="sm">{label}</Text>;
    return <Text size="sm" c="dimmed">—</Text>;
  }

  return <Text size="sm">{String(value)}</Text>;
};
