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

export interface ContractListRow {
  id: string;
  reference: string;
  approvalSteps?: Freight.IContractApprovalStep[];
  customerLabel: string;
  status: string;
  contractKind: Freight.ContractKind;
  tradeDirection: string;
  freightType: string;
  originLabel: string;
  destinationLabel: string;
  validFrom?: string | null;
  validUntil?: string | null;
  validityDays?: number | null;
  isRenewal: boolean;
  createdAt: string;
  customsClearingEnabled: boolean;
  contractGeneratedAt?: string | null;
}

/** The single most relevant next action for a contract row, for the table CTA. */
export type ContractRowAction = {
  label: string;
  to: (id: string) => string;
  variant: "filled" | "light" | "default";
};

/**
 * Map a contract status to its one primary staff action. Returns null when the
 * only action is "open the detail page" (the row click already does that).
 */
export function getStaffRowAction(
  row: Pick<ContractListRow, "status" | "customsClearingEnabled" | "contractGeneratedAt">,
): ContractRowAction | null {
  const detail = (id: string) => `/dashboard/contract-requests/${id}`;
  const view = (id: string) => `/dashboard/contract-requests/${id}/view`;

  switch (row.status) {
    case "SUBMITTED":
      return { label: "Review", to: detail, variant: "filled" };
    case "PENDING_APPROVAL":
      return { label: "Approve", to: detail, variant: "filled" };
    case "CONTRACT_READY":
    case "SIGNED_CUSTOMER":
      return row.contractGeneratedAt
        ? { label: "View & sign", to: view, variant: "filled" }
        : { label: "Open", to: detail, variant: "light" };
    case "CLEARANCE_UNDER_REVIEW":
    case "AWAITING_CLEARANCE_DOCUMENTS":
      return { label: "Review clearance", to: detail, variant: "filled" };
    case "CLEARANCE_READY_FOR_BOOKING":
      return row.customsClearingEnabled
        ? { label: "Create booking", to: detail, variant: "filled" }
        : { label: "Open", to: detail, variant: "light" };
    default:
      return { label: "Open", to: detail, variant: "default" };
  }
}

function yardLabel(
  yard?: { label?: string; code?: string; name?: string } | null,
  fallback = "—",
): string {
  if (!yard) return fallback;
  return yard.label ?? yard.name ?? yard.code ?? fallback;
}

export function toContractListRow(contract: Freight.IContract): ContractListRow {
  const routes = [...(contract.routes ?? [])].sort(
    (a, b) => a.sortOrder - b.sortOrder,
  );
  const first = routes[0];
  const last = routes[routes.length - 1] ?? first;

  return {
    id: contract.id,
    reference: contract.reference,
    approvalSteps: contract.approvalSteps,
    customerLabel: contract.isGovernment
      ? (contract.governmentInstitution ?? "Government")
      : (contract.company?.name ?? "—"),
    status: contract.status,
    contractKind: contract.contractKind,
    tradeDirection: contract.tradeDirection,
    freightType: contract.freightType,
    originLabel: yardLabel(first?.originYard),
    destinationLabel: yardLabel(last?.destinationYard),
    validFrom: contract.contractValidFrom,
    validUntil: contract.contractValidUntil,
    validityDays: contract.contractValidityDays,
    isRenewal: Boolean(contract.renewalOfId),
    createdAt: contract.createdAt,
    customsClearingEnabled: Boolean(contract.customsClearingEnabled),
    contractGeneratedAt: contract.contractGeneratedAt,
  };
}
