import { Freight } from "@edr/types";
import { Badge, Box, Group, Progress, Text, Tooltip } from "@mantine/core";

import type { WagonTransferRequest } from "@/services/wagon.service";

export const yardLabel = (y?: { label?: string; code?: string } | null) =>
  y?.label || y?.code || "—";

export const wagonTypeLabel = (t?: { code?: string; name?: string } | null) =>
  t ? [t.code, t.name].filter(Boolean).join(" · ") : "—";

/** Wagons still owed on a request (0 once it is complete or closed). */
export const outstandingOn = (r: WagonTransferRequest): number =>
  Math.max(0, r.quantity - (r.fulfilledQuantity ?? 0));

/** A request OCC can still move wagons against. */
export const isOpenRequest = (r: WagonTransferRequest): boolean =>
  r.status === Freight.WagonTransferRequestStatus.Pending ||
  r.status === Freight.WagonTransferRequestStatus.PartiallyFulfilled;

export const STATUS_META: Record<string, { label: string; color: string }> = {
  PENDING: { label: "Awaiting wagons", color: "gray" },
  PARTIALLY_FULFILLED: { label: "Partly delivered", color: "yellow" },
  FULFILLED: { label: "Complete", color: "teal" },
  CLOSED_SHORT: { label: "Closed short", color: "orange" },
  CANCELLED: { label: "Cancelled", color: "red" },
};

export function TransferStatusBadge({ status }: { status: string }) {
  const meta = STATUS_META[status] ?? { label: status, color: "gray" };
  return (
    <Badge variant="light" color={meta.color} radius="sm">
      {meta.label}
    </Badge>
  );
}

/**
 * Delivered-vs-asked bar. The number is what staff actually need — the bar just
 * makes "nearly there" vs "barely started" readable at a glance across a page
 * of requests.
 */
export function TransferProgress({ request }: { request: WagonTransferRequest }) {
  const delivered = request.fulfilledQuantity ?? 0;
  const percent = request.quantity > 0 ? (delivered / request.quantity) * 100 : 0;
  const outstanding = outstandingOn(request);
  const complete = delivered >= request.quantity;
  const closedShort =
    request.status === Freight.WagonTransferRequestStatus.ClosedShort;

  return (
    <Tooltip
      withArrow
      label={
        complete
          ? "Fully supplied"
          : closedShort
            ? `Closed ${outstanding} wagon(s) short`
            : `${outstanding} wagon(s) still to come`
      }
    >
      <Box miw={110}>
        <Group gap={6} justify="space-between" wrap="nowrap" mb={4}>
          <Text size="sm" fw={700} style={{ fontVariantNumeric: "tabular-nums" }}>
            {delivered} / {request.quantity}
          </Text>
          {!complete && !closedShort ? (
            <Text size="xs" c="dimmed">
              {outstanding} left
            </Text>
          ) : null}
        </Group>
        <Progress
          value={percent}
          size="sm"
          radius="xl"
          color={complete ? "teal" : closedShort ? "orange" : "yellow"}
        />
      </Box>
    </Tooltip>
  );
}

export const fmtDateTime = (iso?: string | null) =>
  iso
    ? new Date(iso).toLocaleString("en-GB", {
        day: "numeric",
        month: "short",
        hour: "2-digit",
        minute: "2-digit",
        hour12: false,
      })
    : "—";
