import { format } from "date-fns";

import type { Freight } from "@edr/types";

export const isNegative = (s: string) => s === "CANCELLED" || s === "REJECTED";
export const isDraftLike = (s: string) =>
  s === "DRAFT" || s === "CHANGES_REQUESTED";

export function fmtDate(value?: string | null) {
  if (!value) return "—";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? "—" : format(d, "MMM d, yyyy");
}

export function yardLabel(y?: Freight.IBooking["originYard"]) {
  return y?.label ?? y?.code ?? "—";
}

export function containerSummary(b: Freight.IBooking) {
  if (b.containers?.length) {
    return b.containers.map((c) => `${c.qty} × ${c.type}`).join(", ");
  }
  return b.freightType === "BULK" ? "Bulk cargo" : "—";
}

export function bookingSubtitle(b: Freight.IBooking) {
  const cargo =
    b.freightSubtype ||
    (b.freightType === "BULK" ? "Bulk freight" : "Container freight");
  const load = containerSummary(b);
  const route = `${yardLabel(b.originYard)} → ${yardLabel(b.destinationYard)}`;
  return [cargo, load, route].filter((p) => p && p !== "—").join("  ·  ");
}

// ─── Pricing helpers ──────────────────────────────────────────────────────────

export type Pricing = Freight.PricingBreakdown | null | undefined;

export function priceLineItems(pricing: Pricing) {
  return (pricing?.lineItems ?? []).map((li) => ({
    label: li.description,
    value: `${li.amount.toLocaleString()} ${li.currency}`,
  }));
}

export function priceTotal(pricing: Pricing) {
  if (!pricing) return "—";
  const total = pricing.lineItems.reduce((s, li) => s + li.amount, 0);
  return `${total.toLocaleString()} ${pricing.currency}`;
}
