import {
  BadgeCheck,
  ClipboardCheck,
  FileSearch,
  FileText,
  FileUp,
  MapPin,
  PackageCheck,
  PackageOpen,
  ShieldCheck,
  Ship,
  Train,
} from "lucide-react";

export const PROGRESS_STAGES = [
  {
    label: "Request",
    icon: FileText,
    statuses: ["DRAFT", "CHANGES_REQUESTED"],
  },
  {
    // AWAITING_DOCUMENTS: a fresh contract-drawdown booking lands here — the
    // customer just submitted it and now uploads clearance documents.
    label: "Submitted",
    icon: ClipboardCheck,
    statuses: ["SUBMITTED", "AWAITING_DOCUMENTS"],
  },
  {
    // Clearance review is the approval step for contract-drawdown bookings.
    label: "Approval",
    icon: ShieldCheck,
    statuses: [
      "PENDING_APPROVAL",
      "APPROVED_PENDING_SIGNATURE",
      "APPROVED",
      "DOCUMENTS_UNDER_REVIEW",
      "CLEARANCE_READY",
    ],
  },
  {
    label: "Contract",
    icon: ShieldCheck,
    statuses: ["CONTRACT_READY", "SIGNED_CUSTOMER"],
  },
  {
    label: "Payment",
    icon: ShieldCheck,
    statuses: [
      "FULLY_EXECUTED",
      "SELECTED_FOR_BATCH",
      "PAYMENT_VERIFICATION_IN_PROGRESS",
      "OPERATION_REQUESTED",
    ],
  },
  {
    label: "Loading",
    icon: Ship,
    statuses: [
      "PAID",
      "TRUCK_ASSIGNED",
      "PNR_GENERATED",
      "PENDING_CONSOLIDATION",
      "CONSOLIDATED",
    ],
  },
  {
    label: "In Transit",
    icon: Train,
    statuses: ["EXPIRED", "IN_TRANSIT"],
  },
  {
    // The train reached the booking's destination yard — cargo may still be
    // on board. No booking status of its own: it lights up from the assigned
    // train's status (trainScheduleStatus === "ARRIVED") while the booking is
    // still IN_TRANSIT — see resolveStage. Bookings unloaded mid-corridor (or
    // auto-unloaded on a checkpoint) jump straight past it to Unloading.
    label: "Arrival",
    icon: MapPin,
    statuses: [],
  },
  {
    // ARRIVED: cargo unloaded off the train at the booking's own destination
    // yard. Unloading is automatic — the API alights the booking the moment a
    // checkpoint is recorded at its destination yard (or, as a fallback, when
    // the train's final arrival is logged).
    label: "Unloading",
    icon: PackageOpen,
    statuses: ["ARRIVED"],
  },
  {
    label: "Complete",
    icon: PackageCheck,
    statuses: ["COMPLETED", "DELIVERED"],
  },
];

/** Stage index of the Arrival step (train ARRIVED, cargo not yet unloaded). */
export const ARRIVAL_STAGE = PROGRESS_STAGES.findIndex(
  (s) => s.label === "Arrival",
);

/**
 * Progress stages for a CONTRACT-DRAWDOWN booking (created under a contract via
 * initiate → clearance → book). These bookings never pass through the direct
 * wizard's Request/Approval/Contract stages — the contract is already executed.
 * Their journey is: initiated (bare instance in clearance) → submitted (booking
 * completed, sent to operations) → accepted (operations accepted) → payment →
 * loading → transit → arrival → unloading → complete.
 */
export const CONTRACT_PROGRESS_STAGES = [
  {
    // The instance was initiated with one click and now sits in the clearance
    // gate: the customer must upload the required clearance documents.
    label: "Upload Documents",
    icon: FileUp,
    statuses: ["DRAFT", "CHANGES_REQUESTED", "AWAITING_DOCUMENTS"],
  },
  {
    // Staff/GL are reviewing the uploaded clearance documents; the customer
    // only re-uploads queried ones.
    label: "Document Review",
    icon: FileSearch,
    statuses: ["DOCUMENTS_UNDER_REVIEW"],
  },
  {
    // Clearance finished — the customer books (Path A) or GL completes the
    // booking on their behalf (Path B customs).
    label: "Cleared",
    icon: BadgeCheck,
    statuses: ["CLEARANCE_READY"],
  },
  {
    // The customer (or GL) completed the booking — cargo + shipment day — and it
    // is submitted to operations for acceptance.
    label: "Submitted",
    icon: ClipboardCheck,
    statuses: [
      "OPERATION_REQUEST_PENDING",
      "OPERATION_CHANGES_REQUESTED",
      "OPERATION_PRICE_PENDING_CONFIRM",
      "OPERATION_REQUESTED",
    ],
  },
  {
    // Operations accepted the order — it now sits in the batch holding pool
    // awaiting a train and its pay window.
    label: "Accepted",
    icon: ShieldCheck,
    statuses: ["FULLY_EXECUTED", "READY_FOR_ASSIGNMENT"],
  },
  {
    label: "Payment",
    icon: ShieldCheck,
    statuses: [
      "SELECTED_FOR_BATCH",
      "PAYMENT_VERIFICATION_IN_PROGRESS",
      "EXPIRED",
      "PRICE_CHANGED_PENDING_CONFIRM",
    ],
  },
  {
    label: "Loading",
    icon: Ship,
    statuses: [
      "PAID",
      "TRUCK_ASSIGNED",
      "PNR_GENERATED",
      "PENDING_CONSOLIDATION",
      "CONSOLIDATED",
      "WAGON_ASSIGNED",
      "INVOICED",
      "ROAD_DISPATCH_PENDING",
    ],
  },
  {
    label: "In Transit",
    icon: Train,
    statuses: ["IN_TRANSIT"],
  },
  {
    // Lights up from the assigned train's ARRIVED state while the booking is
    // still IN_TRANSIT — no status of its own (see resolveContractStage).
    label: "Arrival",
    icon: MapPin,
    statuses: [],
  },
  {
    label: "Unloading",
    icon: PackageOpen,
    statuses: ["ARRIVED"],
  },
  {
    label: "Complete",
    icon: PackageCheck,
    statuses: ["COMPLETED", "DELIVERED"],
  },
];

/** Contract-drawdown Arrival stage index. */
export const CONTRACT_ARRIVAL_STAGE = CONTRACT_PROGRESS_STAGES.findIndex(
  (s) => s.label === "Arrival",
);

/** status → contract-drawdown stage index, derived from the stage array. */
const CONTRACT_STAGE_BY_STATUS: Record<string, number> = {};
CONTRACT_PROGRESS_STAGES.forEach((stage, index) => {
  stage.statuses.forEach((status) => {
    CONTRACT_STAGE_BY_STATUS[status] = index;
  });
});

/**
 * Contract-drawdown stage for a booking, factoring in the assigned train's
 * status the same way {@link resolveStage} does for direct bookings.
 */
export function resolveContractStage(booking: {
  status: string;
  trainScheduleStatus?: string | null;
}): number {
  if (
    booking.status === "IN_TRANSIT" &&
    booking.trainScheduleStatus === "ARRIVED"
  ) {
    return CONTRACT_ARRIVAL_STAGE;
  }
  return CONTRACT_STAGE_BY_STATUS[booking.status] ?? 0;
}

/**
 * Stage for a booking, factoring in the assigned train's operational status:
 * a booking with per-booking journey data reaches ARRIVED (the Unloading
 * stage) when it is unloaded at its own destination yard; a legacy booking is
 * stuck at IN_TRANSIT between dispatch and delivery, so once its train has
 * ARRIVED the tracker advances to the Arrival stage.
 */
export function resolveStage(booking: {
  status: string;
  trainScheduleStatus?: string | null;
}): number {
  const base = STATUS_MAP[booking.status]?.stage ?? 0;
  if (
    booking.status === "IN_TRANSIT" &&
    booking.trainScheduleStatus === "ARRIVED"
  ) {
    return ARRIVAL_STAGE;
  }
  return base;
}

export const STATUS_MAP: Record<
  string,
  { title: string; description: string; stage: number }
> = {
  DRAFT: {
    title: "Draft — not submitted",
    description:
      "This booking is being prepared and hasn’t been submitted for review yet.",
    stage: 0,
  },
  CHANGES_REQUESTED: {
    title: "Changes requested",
    description: "Staff has requested changes. Please review and resubmit.",
    stage: 0,
  },
  SUBMITTED: {
    title: "Submitted for review",
    description: "Your booking has been submitted and is awaiting review.",
    stage: 1,
  },
  PENDING_APPROVAL: {
    title: "Pending approval",
    description: "Your booking is moving through the approval process.",
    stage: 2,
  },
  APPROVED_PENDING_SIGNATURE: {
    title: "Approved — awaiting signature",
    description: "Approved. Your contract will be ready to sign shortly.",
    stage: 2,
  },
  APPROVED: {
    title: "Approved",
    description: "Your booking has been fully approved.",
    stage: 2,
  },
  CONTRACT_READY: {
    title: "Contract ready to sign",
    description:
      "Your contract is ready. Review and apply your signature to proceed.",
    stage: 3,
  },
  SIGNED_CUSTOMER: {
    title: "Signed — awaiting staff",
    description:
      "Your signature has been submitted. Awaiting the final staff signature.",
    stage: 3,
  },
  FULLY_EXECUTED: {
    title: "Contract fully executed",
    description: "Signed by all parties. You can now proceed to payment.",
    stage: 4,
  },
  SELECTED_FOR_BATCH: {
    title: "Selected for a train — payment due",
    description:
      "Your booking was selected for a scheduled train. Complete payment within the pay window to secure your slot.",
    stage: 4,
  },
  EXPIRED: {
    title: "Pay window expired",
    description:
      "The payment window was missed. You can move this booking to another schedule or cancel it.",
    stage: 6,
  },
  PNR_GENERATED: {
    title: "Payment reference generated",
    description:
      "A payment reference number has been generated for this booking.",
    stage: 5,
  },
  PAYMENT_VERIFICATION_IN_PROGRESS: {
    title: "Verifying payment",
    description: "Your payment is being verified.",
    stage: 4,
  },
  PAID: {
    title: "Payment confirmed",
    description: "Payment has been confirmed for this booking.",
    stage: 5,
  },
  TRUCK_ASSIGNED: {
    title: "Truck assigned",
    description: "Customer truck assigned for self-haul; ready for loading.",
    stage: 5,
  },
  IN_TRANSIT: {
    title: "Cargo moving",
    description: "Your shipment is currently moving through the rail network.",
    stage: 6,
  },
  ARRIVED: {
    title: "Unloaded at destination",
    description:
      "Your cargo has been unloaded at its destination yard and is being prepared for release.",
    stage: 8,
  },
  OPERATION_REQUEST_PENDING: {
    title: "Operation request under review",
    description:
      "Your order has been submitted to operations and is awaiting acceptance.",
    stage: 4,
  },
  OPERATION_CHANGES_REQUESTED: {
    title: "Operation changes requested",
    description: "Operations requested changes to this order. Please review and resubmit.",
    stage: 4,
  },
  OPERATION_PRICE_PENDING_CONFIRM: {
    title: "Price adjusted — confirm to proceed",
    description:
      "Operations adjusted this order's price. Confirm the new price to proceed.",
    stage: 4,
  },
  ROAD_DISPATCH_PENDING: {
    title: "Awaiting truck dispatch",
    description:
      "This road order was accepted and is awaiting truck dispatch. Billed by distance.",
    stage: 5,
  },
  PENDING_CONSOLIDATION: {
    title: "Pending consolidation",
    description: "Awaiting a consolidation partner shipment.",
    stage: 5,
  },
  CONSOLIDATED: {
    title: "Consolidated",
    description: "Cargo has been consolidated with a partner shipment.",
    stage: 5,
  },
  AWAITING_DOCUMENTS: {
    title: "Upload clearance documents",
    description:
      "Upload the required clearance documents so your shipment can be reviewed.",
    stage: 1,
  },
  DOCUMENTS_UNDER_REVIEW: {
    title: "Clearance documents under review",
    description:
      "Your clearance documents are being reviewed. Re-upload any queried documents to proceed.",
    stage: 2,
  },
  CLEARANCE_READY: {
    title: "Cleared — choose a shipment day",
    description:
      "Clearance is complete. Pick a shipment day and proceed to operation.",
    stage: 2,
  },
  OPERATION_REQUESTED: {
    title: "Operation requested",
    description: "Operation requested. An operator will take your shipment forward.",
    stage: 4,
  },
  CONTRACT_ACTIVE: {
    title: "Contract active",
    description: "This general contract is active and accepting drawdown orders.",
    stage: 5,
  },
  CONTRACT_CLOSED: {
    title: "Contract closed",
    description:
      "This general contract is closed — its reserved quantity has been used or its window has elapsed.",
    stage: 9,
  },
  PRICE_CHANGED_PENDING_CONFIRM: {
    title: "Price changed — confirm to proceed",
    description:
      "The price for this booking changed. Confirm the new price to continue.",
    stage: 1,
  },
  READY_FOR_ASSIGNMENT: {
    title: "Awaiting wagon assignment",
    description: "Approved and queued for wagon assignment.",
    stage: 2,
  },
  WAGON_ASSIGNED: {
    title: "Wagon assigned",
    description: "A wagon has been assigned and your cargo is being prepared for loading.",
    stage: 5,
  },
  INVOICED: {
    title: "Invoice issued",
    description: "An invoice has been issued for this booking.",
    stage: 5,
  },
  COMPLETED: {
    title: "Service complete",
    description: "Cargo delivered and service successfully terminated.",
    stage: 9,
  },
  DELIVERED: {
    title: "Service complete",
    description: "Cargo delivered and service successfully terminated.",
    stage: 9,
  },
  REJECTED: {
    title: "Booking rejected",
    description: "This booking request has been rejected.",
    stage: -1,
  },
  CANCELLED: {
    title: "Booking cancelled",
    description: "This booking process has been terminated.",
    stage: -1,
  },
};

export const REQUIRED_DOC_FIELDS = [
  { key: "commercial_invoice", label: "Commercial Invoice" },
  { key: "packing_list", label: "Packing List" },
  { key: "certificate_of_origin", label: "Certificate of Origin" },
  { key: "letter_of_credit", label: "Letter of Credit / LC" },
];
